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.util.Platform;
41 import jalview.viewmodel.ViewportListenerI;
42 import jalview.viewmodel.ViewportRanges;
44 import java.awt.BorderLayout;
45 import java.awt.Color;
46 import java.awt.Container;
47 import java.awt.Dimension;
49 import java.awt.FontMetrics;
50 import java.awt.Graphics;
51 import java.awt.Insets;
52 import java.awt.event.AdjustmentEvent;
53 import java.awt.event.AdjustmentListener;
54 import java.awt.event.ComponentAdapter;
55 import java.awt.event.ComponentEvent;
56 import java.awt.print.PageFormat;
57 import java.awt.print.Printable;
58 import java.awt.print.PrinterException;
59 import java.beans.PropertyChangeEvent;
60 import java.beans.PropertyChangeListener;
62 import java.io.FileWriter;
63 import java.io.PrintWriter;
64 import java.util.List;
66 import javax.swing.SwingUtilities;
72 * @version $Revision: 1.161 $
74 public class AlignmentPanel extends GAlignmentPanel implements
75 AdjustmentListener, Printable, AlignmentViewPanel,
78 public AlignViewport av;
80 ViewportRanges vpRanges;
82 OverviewPanel overviewPanel;
84 private SeqPanel seqPanel;
86 private IdPanel idPanel;
88 private boolean headless;
90 IdwidthAdjuster idwidthAdjuster;
93 public AlignFrame alignFrame;
95 private ScalePanel scalePanel;
97 private AnnotationPanel annotationPanel;
99 private AnnotationLabels alabels;
101 // this value is set false when selection area being dragged
102 boolean fastPaint = true;
104 private int hextent = 0;
106 private int vextent = 0;
109 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
110 * false, suppresses invoking the same method recursively.
112 private boolean scrollComplementaryPanel = true;
114 private PropertyChangeListener propertyChangeListener;
116 private CalculationChooser calculationDialog;
119 * Creates a new AlignmentPanel object.
124 public AlignmentPanel(AlignFrame af, final AlignViewport av)
128 vpRanges = av.getRanges();
129 setSeqPanel(new SeqPanel(av, this));
130 setIdPanel(new IdPanel(av, this));
132 setScalePanel(new ScalePanel(av, this));
134 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
135 idwidthAdjuster = new IdwidthAdjuster(this);
136 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
138 setAnnotationPanel(new AnnotationPanel(this));
139 setAlabels(new AnnotationLabels(this));
141 annotationScroller.setViewportView(getAnnotationPanel());
142 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
144 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
145 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
147 setScrollValues(0, 0);
149 hscroll.addAdjustmentListener(this);
150 vscroll.addAdjustmentListener(this);
152 addComponentListener(new ComponentAdapter()
155 public void componentResized(ComponentEvent evt)
157 // reset the viewport ranges when the alignment panel is resized
158 // in particular, this initialises the end residue value when Jalview
160 if (av.getWrapAlignment())
162 int widthInRes = getSeqPanel().seqCanvas
163 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
164 vpRanges.setViewportWidth(widthInRes);
168 int widthInRes = getSeqPanel().seqCanvas.getWidth()
170 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
171 / av.getCharHeight();
173 vpRanges.setViewportWidth(widthInRes);
174 vpRanges.setViewportHeight(heightInSeq);
180 final AlignmentPanel ap = this;
181 propertyChangeListener = new PropertyChangeListener()
184 public void propertyChange(PropertyChangeEvent evt)
186 if (evt.getPropertyName().equals("alignment"))
188 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
193 av.addPropertyChangeListener(propertyChangeListener);
195 av.getRanges().addPropertyChangeListener(this);
197 adjustAnnotationHeight();
202 public AlignViewportI getAlignViewport()
207 public void alignmentChanged()
209 av.alignmentChanged(this);
211 if (getCalculationDialog() != null)
213 getCalculationDialog().validateCalcTypes();
216 alignFrame.updateEditMenuBar();
218 paintAlignment(true);
225 public void fontChanged()
227 // set idCanvas bufferedImage to null
228 // to prevent drawing old image
229 FontMetrics fm = getFontMetrics(av.getFont());
231 scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
233 idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
234 .getCharHeight() + fm.getDescent()));
236 getIdPanel().getIdCanvas().gg = null;
237 getSeqPanel().seqCanvas.img = null;
238 getAnnotationPanel().adjustPanelHeight();
240 Dimension d = calculateIdWidth();
242 d.setSize(d.width + 4, d.height);
243 getIdPanel().getIdCanvas().setPreferredSize(d);
244 hscrollFillerPanel.setPreferredSize(d);
246 if (this.alignFrame.getSplitViewContainer() != null)
248 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
255 * Calculate the width of the alignment labels based on the displayed names
256 * and any bounds on label width set in preferences.
258 * @return Dimension giving the maximum width of the alignment label panel
259 * that should be used.
261 public Dimension calculateIdWidth()
263 // calculate sensible default width when no preference is available
265 if (av.getIdWidth() < 0)
267 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
268 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
269 r = calculateIdWidth(maxwidth);
270 av.setIdWidth(r.width);
275 r.width = av.getIdWidth();
282 * Calculate the width of the alignment labels based on the displayed names
283 * and any bounds on label width set in preferences.
286 * -1 or maximum width allowed for IdWidth
287 * @return Dimension giving the maximum width of the alignment label panel
288 * that should be used.
290 public Dimension calculateIdWidth(int maxwidth)
292 Container c = new Container();
294 FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
295 Font.ITALIC, av.font.getSize()));
297 AlignmentI al = av.getAlignment();
302 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
304 SequenceI s = al.getSequenceAt(i);
306 id = s.getDisplayId(av.getShowJVSuffix());
308 if (fm.stringWidth(id) > idWidth)
310 idWidth = fm.stringWidth(id);
316 // Also check annotation label widths
319 if (al.getAlignmentAnnotation() != null)
321 fm = c.getFontMetrics(getAlabels().getFont());
323 while (i < al.getAlignmentAnnotation().length)
325 String label = al.getAlignmentAnnotation()[i].label;
327 if (fm.stringWidth(label) > idWidth)
329 idWidth = fm.stringWidth(label);
336 return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
341 * Highlight the given results on the alignment.
344 public void highlightSearchResults(SearchResultsI results)
346 scrollToPosition(results);
347 getSeqPanel().seqCanvas.highlightSearchResults(results);
351 * Scroll the view to show the position of the highlighted region in results
352 * (if any) and redraw the overview
356 public boolean scrollToPosition(SearchResultsI results)
358 return scrollToPosition(results, 0, true, false);
362 * Scroll the view to show the position of the highlighted region in results
365 * @param searchResults
366 * @param redrawOverview
369 public boolean scrollToPosition(SearchResultsI searchResults,
370 boolean redrawOverview)
372 return scrollToPosition(searchResults, 0, redrawOverview, false);
376 * Scroll the view to show the position of the highlighted region in results
380 * @param verticalOffset
381 * if greater than zero, allows scrolling to a position below the
382 * first displayed sequence
383 * @param redrawOverview
384 * - when set, the overview will be recalculated (takes longer)
386 * if true, try to centre the search results horizontally in the view
387 * @return false if results were not found
389 public boolean scrollToPosition(SearchResultsI results,
390 int verticalOffset, boolean redrawOverview, boolean centre)
392 int startv, endv, starts, ends;
393 // TODO: properly locate search results in view when large numbers of hidden
394 // columns exist before highlighted region
395 // do we need to scroll the panel?
396 // TODO: tons of nullpointerexceptions raised here.
397 if (results != null && results.getSize() > 0 && av != null
398 && av.getAlignment() != null)
400 int seqIndex = av.getAlignment().findIndex(results);
405 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
407 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
416 * To centre results, scroll to positions half the visible width
417 * left/right of the start/end positions
421 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2
423 start = Math.max(start - offset, 0);
424 end = end + offset - 1;
430 if (end == seq.getEnd())
434 if (av.hasHiddenColumns())
436 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
437 start = hidden.findColumnPosition(start);
438 end = hidden.findColumnPosition(end);
441 if (!hidden.isVisible(r[0]))
443 // don't scroll - position isn't visible
450 * allow for offset of target sequence (actually scroll to one above it)
452 seqIndex = Math.max(0, seqIndex - verticalOffset);
454 if (!av.getWrapAlignment())
456 if ((startv = vpRanges.getStartRes()) >= start)
459 * Scroll left to make start of search results visible
461 setScrollValues(start, seqIndex);
463 else if ((endv = vpRanges.getEndRes()) <= end)
466 * Scroll right to make end of search results visible
468 setScrollValues(startv + end - endv, seqIndex);
470 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
473 * Scroll up to make start of search results visible
475 setScrollValues(vpRanges.getStartRes(), seqIndex);
477 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
480 * Scroll down to make end of search results visible
482 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
486 * Else results are already visible - no need to scroll
491 vpRanges.scrollToWrappedVisible(start);
495 paintAlignment(redrawOverview);
502 * @return DOCUMENT ME!
504 public OverviewPanel getOverviewPanel()
506 return overviewPanel;
515 public void setOverviewPanel(OverviewPanel op)
523 * Hide or show annotation panel
526 public void setAnnotationVisible(boolean b)
528 if (!av.getWrapAlignment())
530 annotationSpaceFillerHolder.setVisible(b);
531 annotationScroller.setVisible(b);
537 * automatically adjust annotation panel height for new annotation whilst
538 * ensuring the alignment is still visible.
541 public void adjustAnnotationHeight()
543 // TODO: display vertical annotation scrollbar if necessary
544 // this is called after loading new annotation onto alignment
545 if (alignFrame.getHeight() == 0)
547 System.out.println("NEEDS FIXING");
549 validateAnnotationDimensions(true);
551 paintAlignment(true);
555 * calculate the annotation dimensions and refresh slider values accordingly.
556 * need to do repaints/notifys afterwards.
558 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
560 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
562 if (adjustPanelHeight)
564 int rowHeight = av.getCharHeight();
565 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
568 * Estimate available height in the AlignFrame for alignment +
569 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
570 * hscroll, status bar (as these are not laid out we can't inspect their
571 * actual heights). Insets gives frame borders.
573 int stuff = Platform.isAMac() ? 80 : 100;
574 Insets insets = alignFrame.getInsets();
575 int availableHeight = alignFrame.getHeight() - stuff - insets.top
579 * If not enough vertical space, maximize annotation height while keeping
580 * at least two rows of alignment visible
582 if (annotationHeight + alignmentHeight > availableHeight)
584 annotationHeight = Math.min(annotationHeight, availableHeight - 2
590 // maintain same window layout whilst updating sliders
591 annotationHeight = annotationScroller.getSize().height;
595 annotationScroller.setPreferredSize(new Dimension(annotationScroller
596 .getWidth(), annotationHeight));
598 Dimension e = idPanel.getSize();
599 alabels.setSize(new Dimension(e.width, annotationHeight));
601 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
602 annotationSpaceFillerHolder.getWidth(), annotationHeight));
603 annotationScroller.validate();
604 annotationScroller.addNotify();
608 * update alignment layout for viewport settings
613 public void updateLayout()
616 setAnnotationVisible(av.isShowAnnotation());
617 boolean wrap = av.getWrapAlignment();
618 vpRanges.setStartSeq(0);
619 scalePanelHolder.setVisible(!wrap);
620 hscroll.setVisible(!wrap);
621 idwidthAdjuster.setVisible(!wrap);
625 annotationScroller.setVisible(false);
626 annotationSpaceFillerHolder.setVisible(false);
628 else if (av.isShowAnnotation())
630 annotationScroller.setVisible(true);
631 annotationSpaceFillerHolder.setVisible(true);
636 int widthInRes = getSeqPanel().seqCanvas
637 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
638 vpRanges.setViewportWidth(widthInRes);
642 int widthInRes = (getSeqPanel().seqCanvas.getWidth() / av
643 .getCharWidth()) - 1;
644 int heightInSeq = (getSeqPanel().seqCanvas.getHeight() / av
645 .getCharHeight()) - 1;
647 vpRanges.setViewportWidth(widthInRes);
648 vpRanges.setViewportHeight(heightInSeq);
651 idSpaceFillerPanel1.setVisible(!wrap);
658 * Adjust row/column scrollers to show a visible position in the alignment.
661 * visible column to scroll to
663 * visible row to scroll to
666 public void setScrollValues(int xpos, int ypos)
671 if (av == null || av.getAlignment() == null)
676 if (av.getWrapAlignment())
678 setScrollingForWrappedPanel(x);
682 int width = av.getAlignment().getWidth();
683 int height = av.getAlignment().getHeight();
685 if (av.hasHiddenColumns())
687 // reset the width to exclude hidden columns
688 width = av.getAlignment().getHiddenColumns().findColumnPosition(width);
691 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
692 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
699 if (vextent > height)
704 if ((hextent + x) > width)
709 if ((vextent + y) > height)
711 y = height - vextent;
724 // update the scroll values
725 hscroll.setValues(x, hextent, 0, width);
726 vscroll.setValues(y, vextent, 0, height);
731 * Respond to adjustment event when horizontal or vertical scrollbar is
735 * adjustment event encoding whether hscroll or vscroll changed
738 public void adjustmentValueChanged(AdjustmentEvent evt)
740 int oldX = vpRanges.getStartRes();
741 int oldwidth = vpRanges.getViewportWidth();
742 int oldY = vpRanges.getStartSeq();
743 int oldheight = vpRanges.getViewportHeight();
745 if (av.getWrapAlignment())
747 if (evt.getSource() == hscroll)
749 return; // no horizontal scroll when wrapped
751 else if (evt.getSource() == vscroll)
753 int offy = vscroll.getValue();
754 int rowSize = getSeqPanel().seqCanvas
755 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
757 // if we're scrolling to the position we're already at, stop
758 // this prevents infinite recursion of events when the scroll/viewport
759 // ranges values are the same
760 int newX = offy * rowSize;
761 if ((newX == oldX) && (oldwidth == rowSize))
768 * throttle to one width's worth at a time (so click in
769 * scrollbar doesn't jump over data)
771 newX = newX > oldX ? oldX + rowSize : oldX - rowSize;
772 vpRanges.setViewportStartAndWidth(newX, rowSize);
777 // This is only called if file loaded is a jar file that
778 // was wrapped when saved and user has wrap alignment true
779 // as preference setting
780 SwingUtilities.invokeLater(new Runnable()
785 // When updating scrolling to use ViewportChange events, this code
786 // could not be validated and it is not clear if it is now being
787 // called. Log warning here in case it is called and unforeseen
790 .warn("Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
792 // scroll to start of panel
793 vpRanges.setStartRes(0);
794 vpRanges.setStartSeq(0);
803 if (evt.getSource() == hscroll)
805 int x = hscroll.getValue();
806 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
808 // if we're scrolling to the position we're already at, stop
809 // this prevents infinite recursion of events when the scroll/viewport
810 // ranges values are the same
811 if ((x == oldX) && (width == oldwidth))
815 vpRanges.setViewportStartAndWidth(x, width);
817 else if (evt.getSource() == vscroll)
819 int y = vscroll.getValue();
820 int height = getSeqPanel().seqCanvas.getHeight()
821 / av.getCharHeight();
823 // if we're scrolling to the position we're already at, stop
824 // this prevents infinite recursion of events when the scroll/viewport
825 // ranges values are the same
826 if ((y == oldY) && (height == oldheight))
830 vpRanges.setViewportStartAndHeight(y, height);
840 * Repaint the alignment including the annotations and overview panels (if
844 public void paintAlignment(boolean updateOverview)
846 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
847 av.isShowAutocalculatedAbove());
848 sorter.sort(getAlignment().getAlignmentAnnotation(),
849 av.getSortAnnotationsBy());
854 // TODO: determine if this paintAlignment changed structure colours
855 av.getStructureSelectionManager().sequenceColoursChanged(this);
857 if (overviewPanel != null)
859 overviewPanel.updateOverviewImage();
871 public void paintComponent(Graphics g)
875 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
876 idPanelHolder.setPreferredSize(d);
877 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
881 * set scroll bar positions
883 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
887 * Set vertical scroll bar parameters for wrapped panel
889 * the residue to scroll to
891 private void setScrollingForWrappedPanel(int res)
893 // get the width of the alignment in residues
894 int maxwidth = av.getAlignment().getWidth();
895 if (av.hasHiddenColumns())
897 maxwidth = av.getAlignment().getHiddenColumns()
898 .findColumnPosition(maxwidth) - 1;
901 // get the width of the canvas in residues
902 int canvasWidth = getSeqPanel().seqCanvas
903 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
906 // position we want to scroll to is number of canvasWidth's to get there
907 int current = res / canvasWidth;
909 // max scroll position: add one because extent is 1 and scrollbar value
910 // can only be set to at most max - extent
911 int max = maxwidth / canvasWidth + 1;
912 vscroll.setUnitIncrement(1);
913 vscroll.setValues(current, 1, 0, max);
927 * @return DOCUMENT ME!
929 * @throws PrinterException
933 public int print(Graphics pg, PageFormat pf, int pi)
934 throws PrinterException
936 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
938 int pwidth = (int) pf.getImageableWidth();
939 int pheight = (int) pf.getImageableHeight();
941 if (av.getWrapAlignment())
943 return printWrappedAlignment(pwidth, pheight, pi, pg);
947 return printUnwrapped(pwidth, pheight, pi, pg, pg);
963 * @return DOCUMENT ME!
965 * @throws PrinterException
969 * Draws the alignment image, including sequence ids, sequences, and
970 * annotation labels and annotations if shown, on either one or two Graphics
977 * the graphics context for sequence ids and annotation labels
978 * @param alignmentGraphics
979 * the graphics context for sequences and annotations (may or may not
980 * be the same context as idGraphics)
982 * @throws PrinterException
984 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
985 Graphics idGraphics, Graphics alignmentGraphics)
986 throws PrinterException
988 final int idWidth = getVisibleIdWidth(false);
991 * Get the horizontal offset to where we draw the sequences.
992 * This is idWidth if using a single Graphics context, else zero.
994 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
996 FontMetrics fm = getFontMetrics(av.getFont());
997 int charHeight = av.getCharHeight();
998 int scaleHeight = charHeight + fm.getDescent();
1000 idGraphics.setColor(Color.white);
1001 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1002 idGraphics.setFont(av.getFont());
1005 * How many sequences and residues can we fit on a printable page?
1007 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1009 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1011 int alignmentWidth = av.getAlignment().getWidth();
1012 int pagesWide = (alignmentWidth / totalRes) + 1;
1014 final int startRes = (pi % pagesWide) * totalRes;
1015 int endRes = (startRes + totalRes) - 1;
1017 if (endRes > (alignmentWidth - 1))
1019 endRes = alignmentWidth - 1;
1022 final int startSeq = (pi / pagesWide) * totalSeq;
1023 int endSeq = startSeq + totalSeq;
1025 int alignmentHeight = av.getAlignment().getHeight();
1026 if (endSeq > alignmentHeight)
1028 endSeq = alignmentHeight;
1031 int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1034 if (av.isShowAnnotation())
1036 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1039 pagesHigh /= pageHeight;
1041 if (pi >= (pagesWide * pagesHigh))
1043 return Printable.NO_SUCH_PAGE;
1045 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1049 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1051 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1052 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1053 pageWidth - idWidth, scaleHeight);
1054 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1057 * Draw the sequence ids, offset for scale height,
1058 * then reset to top left (0, 0)
1060 idGraphics.translate(0, scaleHeight);
1061 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1062 Color currentColor = null;
1063 Color currentTextColor = null;
1066 for (int i = startSeq; i < endSeq; i++)
1068 seq = av.getAlignment().getSequenceAt(i);
1069 if ((av.getSelectionGroup() != null)
1070 && av.getSelectionGroup().getSequences(null).contains(seq))
1073 * gray out ids of sequences in selection group (if any)
1075 currentColor = Color.gray;
1076 currentTextColor = Color.black;
1080 currentColor = av.getSequenceColour(seq);
1081 currentTextColor = Color.black;
1084 idGraphics.setColor(currentColor);
1085 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1088 idGraphics.setColor(currentTextColor);
1091 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1092 if (av.isRightAlignIds())
1094 fm = idGraphics.getFontMetrics();
1096 - fm.stringWidth(displayId)
1100 idGraphics.drawString(displayId, xPos,
1101 (((i - startSeq) * charHeight) + charHeight)
1102 - (charHeight / 5));
1104 idGraphics.setFont(av.getFont());
1105 idGraphics.translate(0, -scaleHeight);
1108 * draw the sequences, offset for scale height, and id width (if using a
1109 * single graphics context), then reset to (0, scale height)
1111 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1112 getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1113 startSeq, endSeq, 0);
1114 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1116 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1119 * draw annotation labels; drawComponent() translates by
1120 * getScrollOffset(), so compensate for that first;
1121 * then reset to (0, scale height)
1123 int offset = getAlabels().getScrollOffset();
1124 idGraphics.translate(0, -offset);
1125 idGraphics.translate(0, alignmentDrawnHeight);
1126 getAlabels().drawComponent(idGraphics, idWidth);
1127 idGraphics.translate(0, -alignmentDrawnHeight);
1130 * draw the annotations starting at
1131 * (idOffset, alignmentHeight) from (0, scaleHeight)
1133 alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1134 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1135 alignmentGraphics, -1, startRes, endRes + 1);
1138 return Printable.PAGE_EXISTS;
1153 * @return DOCUMENT ME!
1155 * @throws PrinterException
1158 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1159 Graphics pg) throws PrinterException
1161 int annotationHeight = 0;
1162 AnnotationLabels labels = null;
1163 if (av.isShowAnnotation())
1165 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1166 labels = new AnnotationLabels(av);
1169 int hgap = av.getCharHeight();
1170 if (av.getScaleAboveWrapped())
1172 hgap += av.getCharHeight();
1175 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1178 int idWidth = getVisibleIdWidth(false);
1180 int maxwidth = av.getAlignment().getWidth();
1181 if (av.hasHiddenColumns())
1183 maxwidth = av.getAlignment().getHiddenColumns()
1184 .findColumnPosition(maxwidth) - 1;
1187 int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1190 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1192 pg.setColor(Color.white);
1193 pg.fillRect(0, 0, pwidth, pheight);
1194 pg.setFont(av.getFont());
1198 pg.setColor(Color.black);
1200 pg.translate(0, -pi * pheight);
1202 pg.setClip(0, pi * pheight, pwidth, pheight);
1208 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1210 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1211 SequenceI s = av.getAlignment().getSequenceAt(i);
1212 String string = s.getDisplayId(av.getShowJVSuffix());
1214 if (av.isRightAlignIds())
1216 FontMetrics fm = pg.getFontMetrics();
1217 xPos = idWidth - fm.stringWidth(string) - 4;
1219 pg.drawString(string, xPos,
1220 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1221 - (av.getCharHeight() / 5));
1226 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1228 pg.setFont(av.getFont());
1229 labels.drawComponent(pg, idWidth);
1233 - (av.getAlignment().getHeight() * av
1238 } while (ypos < totalHeight);
1240 pg.translate(idWidth, 0);
1242 getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1245 if ((pi * pheight) < totalHeight)
1247 return Printable.PAGE_EXISTS;
1252 return Printable.NO_SUCH_PAGE;
1257 * get current sequence ID panel width, or nominal value if panel were to be
1258 * displayed using default settings
1262 public int getVisibleIdWidth()
1264 return getVisibleIdWidth(true);
1268 * get current sequence ID panel width, or nominal value if panel were to be
1269 * displayed using default settings
1272 * indicate if the Id width for onscreen or offscreen display should
1276 public int getVisibleIdWidth(boolean onscreen)
1278 // see if rendering offscreen - check preferences and calc width accordingly
1279 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1281 return calculateIdWidth(-1).width + 4;
1283 Integer idwidth = null;
1285 || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1287 int w = getIdPanel().getWidth();
1288 return (w > 0 ? w : calculateIdWidth().width + 4);
1290 return idwidth.intValue() + 4;
1293 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1295 int boarderBottomOffset = 5;
1296 long pSessionId = System.currentTimeMillis();
1297 headless = (System.getProperty("java.awt.headless") != null && System
1298 .getProperty("java.awt.headless").equals("true"));
1299 if (alignFrame != null && !headless)
1303 alignFrame.setProgressBar(MessageManager.formatMessage(
1304 "status.saving_file", new Object[] { type.getLabel() }),
1310 AlignmentDimension aDimension = getAlignmentDimension();
1313 jalview.util.ImageMaker im;
1314 final String imageAction, imageTitle;
1315 if (type == jalview.util.ImageMaker.TYPE.PNG)
1317 imageAction = "Create PNG image from alignment";
1320 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1322 imageAction = "Create EPS file from alignment";
1323 imageTitle = alignFrame.getTitle();
1327 imageAction = "Create SVG file from alignment";
1328 imageTitle = alignFrame.getTitle();
1331 im = new jalview.util.ImageMaker(this, type, imageAction,
1332 aDimension.getWidth(), aDimension.getHeight()
1333 + boarderBottomOffset, file, imageTitle,
1334 alignFrame, pSessionId, headless);
1335 Graphics graphics = im.getGraphics();
1336 if (av.getWrapAlignment())
1338 if (graphics != null)
1340 printWrappedAlignment(aDimension.getWidth(),
1341 aDimension.getHeight() + boarderBottomOffset, 0,
1348 if (graphics != null)
1350 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1351 0, graphics, graphics);
1356 } catch (OutOfMemoryError err)
1359 System.out.println("########################\n" + "OUT OF MEMORY "
1360 + file + "\n" + "########################");
1361 new OOMWarning("Creating Image for " + file, err);
1362 // System.out.println("Create IMAGE: " + err);
1363 } catch (Exception ex)
1365 ex.printStackTrace();
1373 public AlignmentDimension getAlignmentDimension()
1375 int maxwidth = av.getAlignment().getWidth();
1376 if (av.hasHiddenColumns())
1378 maxwidth = av.getAlignment().getHiddenColumns()
1379 .findColumnPosition(maxwidth);
1382 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1383 + getScalePanel().getHeight();
1384 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1386 if (av.getWrapAlignment())
1388 height = getWrappedHeight();
1391 // need to obtain default alignment width and then add in any
1392 // additional allowance for id margin
1393 // this duplicates the calculation in getWrappedHeight but adjusts for
1395 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1396 - alignFrame.getInsets().left
1397 - alignFrame.getInsets().right - getVisibleIdWidth()
1398 + getVisibleIdWidth(false);
1402 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1406 else if (av.isShowAnnotation())
1408 height += getAnnotationPanel().adjustPanelHeight() + 3;
1410 return new AlignmentDimension(width, height);
1417 public void makeEPS(File epsFile)
1419 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1425 public void makePNG(File pngFile)
1427 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1430 public void makeSVG(File svgFile)
1432 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1435 public void makePNGImageMap(File imgMapFile, String imageName)
1437 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1438 // ////////////////////////////////////////////
1439 int idWidth = getVisibleIdWidth(false);
1440 FontMetrics fm = getFontMetrics(av.getFont());
1441 int scaleHeight = av.getCharHeight() + fm.getDescent();
1444 // ////////////////////////////////
1445 if (imgMapFile != null)
1449 int sSize = av.getAlignment().getHeight();
1450 int alwidth = av.getAlignment().getWidth();
1451 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1452 out.println(HTMLOutput.getImageMapHTML());
1453 out.println("<img src=\"" + imageName
1454 + "\" border=\"0\" usemap=\"#Map\" >"
1455 + "<map name=\"Map\">");
1457 for (int s = 0; s < sSize; s++)
1459 int sy = s * av.getCharHeight() + scaleHeight;
1461 SequenceI seq = av.getAlignment().getSequenceAt(s);
1462 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1463 for (int column = 0; column < alwidth; column++)
1465 StringBuilder text = new StringBuilder(512);
1466 String triplet = null;
1467 if (av.getAlignment().isNucleotide())
1469 triplet = ResidueProperties.nucleotideName.get(seq
1470 .getCharAt(column) + "");
1474 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1478 if (triplet == null)
1483 int seqPos = seq.findPosition(column);
1484 int gSize = groups.length;
1485 for (int g = 0; g < gSize; g++)
1487 if (text.length() < 1)
1489 text.append("<area shape=\"rect\" coords=\"")
1490 .append((idWidth + column * av.getCharWidth()))
1491 .append(",").append(sy).append(",")
1492 .append((idWidth + (column + 1) * av.getCharWidth()))
1493 .append(",").append((av.getCharHeight() + sy))
1494 .append("\"").append(" onMouseOver=\"toolTip('")
1495 .append(seqPos).append(" ").append(triplet);
1498 if (groups[g].getStartRes() < column
1499 && groups[g].getEndRes() > column)
1501 text.append("<br><em>").append(groups[g].getName())
1506 if (text.length() < 1)
1508 text.append("<area shape=\"rect\" coords=\"")
1509 .append((idWidth + column * av.getCharWidth()))
1510 .append(",").append(sy).append(",")
1511 .append((idWidth + (column + 1) * av.getCharWidth()))
1512 .append(",").append((av.getCharHeight() + sy))
1513 .append("\"").append(" onMouseOver=\"toolTip('")
1514 .append(seqPos).append(" ").append(triplet);
1516 if (!Comparison.isGap(seq.getCharAt(column)))
1518 List<SequenceFeature> features = seq.findFeatures(column, column);
1519 for (SequenceFeature sf : features)
1521 if (sf.isContactFeature())
1523 text.append("<br>").append(sf.getType()).append(" ")
1524 .append(sf.getBegin()).append(":")
1525 .append(sf.getEnd());
1529 text.append("<br>");
1530 text.append(sf.getType());
1531 String description = sf.getDescription();
1532 if (description != null
1533 && !sf.getType().equals(description))
1535 description = description.replace("\"", """);
1536 text.append(" ").append(description);
1539 String status = sf.getStatus();
1540 if (status != null && !"".equals(status))
1542 text.append(" (").append(status).append(")");
1545 if (text.length() > 1)
1547 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1548 out.println(text.toString());
1553 out.println("</map></body></html>");
1556 } catch (Exception ex)
1558 ex.printStackTrace();
1560 } // /////////END OF IMAGE MAP
1564 int getWrappedHeight()
1566 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1568 if (System.getProperty("java.awt.headless") != null
1569 && System.getProperty("java.awt.headless").equals("true"))
1571 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1572 - vscroll.getPreferredSize().width
1573 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1576 int chunkWidth = getSeqPanel().seqCanvas
1577 .getWrappedCanvasWidth(seqPanelWidth);
1579 int hgap = av.getCharHeight();
1580 if (av.getScaleAboveWrapped())
1582 hgap += av.getCharHeight();
1585 int annotationHeight = 0;
1586 if (av.isShowAnnotation())
1588 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1591 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1594 int maxwidth = av.getAlignment().getWidth();
1595 if (av.hasHiddenColumns())
1597 maxwidth = av.getAlignment().getHiddenColumns()
1598 .findColumnPosition(maxwidth) - 1;
1601 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1607 * close the panel - deregisters all listeners and nulls any references to
1610 public void closePanel()
1612 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1613 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1614 PaintRefresher.RemoveComponent(this);
1619 * try to ensure references are nulled
1621 if (annotationPanel != null)
1623 annotationPanel.dispose();
1628 av.removePropertyChangeListener(propertyChangeListener);
1629 jalview.structure.StructureSelectionManager ssm = av
1630 .getStructureSelectionManager();
1631 ssm.removeStructureViewerListener(getSeqPanel(), null);
1632 ssm.removeSelectionListener(getSeqPanel());
1633 ssm.removeCommandListener(av);
1634 ssm.removeStructureViewerListener(getSeqPanel(), null);
1635 ssm.removeSelectionListener(getSeqPanel());
1641 if (Cache.log.isDebugEnabled())
1643 Cache.log.warn("Closing alignment panel which is already closed.");
1649 * Close any open dialogs that would be orphaned when this one is closed
1651 protected void closeChildFrames()
1653 if (calculationDialog != null)
1655 calculationDialog.closeFrame();
1660 * hides or shows dynamic annotation rows based on groups and av state flags
1662 public void updateAnnotation()
1664 updateAnnotation(false, false);
1667 public void updateAnnotation(boolean applyGlobalSettings)
1669 updateAnnotation(applyGlobalSettings, false);
1672 public void updateAnnotation(boolean applyGlobalSettings,
1673 boolean preserveNewGroupSettings)
1675 av.updateGroupAnnotationSettings(applyGlobalSettings,
1676 preserveNewGroupSettings);
1677 adjustAnnotationHeight();
1681 public AlignmentI getAlignment()
1683 return av == null ? null : av.getAlignment();
1687 public String getViewName()
1693 * Make/Unmake this alignment panel the current input focus
1697 public void setSelected(boolean b)
1701 if (alignFrame.getSplitViewContainer() != null)
1704 * bring enclosing SplitFrame to front first if there is one
1706 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1708 alignFrame.setSelected(b);
1709 } catch (Exception ex)
1715 alignFrame.setDisplayedView(this);
1720 public StructureSelectionManager getStructureSelectionManager()
1722 return av.getStructureSelectionManager();
1726 public void raiseOOMWarning(String string, OutOfMemoryError error)
1728 new OOMWarning(string, error, this);
1732 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1735 return new FeatureRenderer(this);
1739 public jalview.api.FeatureRenderer getFeatureRenderer()
1741 return seqPanel.seqCanvas.getFeatureRenderer();
1744 public void updateFeatureRenderer(
1745 jalview.renderer.seqfeatures.FeatureRenderer fr)
1747 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1750 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1752 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1754 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1758 public ScalePanel getScalePanel()
1763 public void setScalePanel(ScalePanel scalePanel)
1765 this.scalePanel = scalePanel;
1768 public SeqPanel getSeqPanel()
1773 public void setSeqPanel(SeqPanel seqPanel)
1775 this.seqPanel = seqPanel;
1778 public AnnotationPanel getAnnotationPanel()
1780 return annotationPanel;
1783 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1785 this.annotationPanel = annotationPanel;
1788 public AnnotationLabels getAlabels()
1793 public void setAlabels(AnnotationLabels alabels)
1795 this.alabels = alabels;
1798 public IdPanel getIdPanel()
1803 public void setIdPanel(IdPanel idPanel)
1805 this.idPanel = idPanel;
1809 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1810 * The aim is to keep the two alignments 'lined up' on their centre columns.
1813 * holds mapped region(s) of this alignment that we are scrolling
1814 * 'to'; may be modified for sequence offset by this method
1815 * @param verticalOffset
1816 * the number of visible sequences to show above the mapped region
1818 public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1821 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1822 * mapped), we can make the scroll-to location a sequence above the one
1825 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1826 List<SequenceI> seqs = av.getAlignment().getSequences();
1829 * This is like AlignmentI.findIndex(seq) but here we are matching the
1830 * dataset sequence not the aligned sequence
1832 boolean matched = false;
1833 for (SequenceI seq : seqs)
1835 if (mappedTo == seq.getDatasetSequence())
1843 return; // failsafe, shouldn't happen
1847 * Scroll to position but centring the target residue.
1849 scrollToPosition(sr, verticalOffset, true, true);
1853 * Set a flag to say do not scroll any (cDNA/protein) complement.
1857 protected void setToScrollComplementPanel(boolean b)
1859 this.scrollComplementaryPanel = b;
1863 * Get whether to scroll complement panel
1865 * @return true if cDNA/protein complement panels should be scrolled
1867 protected boolean isSetToScrollComplementPanel()
1869 return this.scrollComplementaryPanel;
1875 * @adjustHeight if true, try to recalculate panel height for visible
1878 protected void refresh(boolean adjustHeight)
1880 validateAnnotationDimensions(adjustHeight);
1884 // sort, repaint, update overview
1885 paintAlignment(true);
1889 // lightweight repaint
1896 * Property change event fired when a change is made to the viewport ranges
1897 * object associated with this alignment panel's viewport
1899 public void propertyChange(PropertyChangeEvent evt)
1901 // update this panel's scroll values based on the new viewport ranges values
1902 int x = vpRanges.getStartRes();
1903 int y = vpRanges.getStartSeq();
1904 setScrollValues(x, y);
1906 // now update any complementary alignment (its viewport ranges object
1907 // is different so does not get automatically updated)
1908 if (isSetToScrollComplementPanel())
1910 setToScrollComplementPanel(false);
1911 av.scrollComplementaryAlignment();
1912 setToScrollComplementPanel(true);
1917 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1918 * reference should be nulled when the dialog is closed.
1920 * @param calculationChooser
1922 public void setCalculationDialog(CalculationChooser calculationChooser)
1924 calculationDialog = calculationChooser;
1928 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1931 public CalculationChooser getCalculationDialog()
1933 return calculationDialog;