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.jbgui.GAlignmentPanel;
34 import jalview.math.AlignmentDimension;
35 import jalview.schemes.ResidueProperties;
36 import jalview.structure.StructureSelectionManager;
37 import jalview.util.Comparison;
38 import jalview.util.MessageManager;
39 import jalview.util.Platform;
40 import jalview.viewmodel.ViewportRanges;
42 import java.awt.BorderLayout;
43 import java.awt.Color;
44 import java.awt.Container;
45 import java.awt.Dimension;
47 import java.awt.FontMetrics;
48 import java.awt.Graphics;
49 import java.awt.Insets;
50 import java.awt.event.AdjustmentEvent;
51 import java.awt.event.AdjustmentListener;
52 import java.awt.print.PageFormat;
53 import java.awt.print.Printable;
54 import java.awt.print.PrinterException;
55 import java.beans.PropertyChangeEvent;
56 import java.beans.PropertyChangeListener;
58 import java.io.FileWriter;
59 import java.io.PrintWriter;
60 import java.util.List;
62 import javax.swing.SwingUtilities;
68 * @version $Revision: 1.161 $
70 public class AlignmentPanel extends GAlignmentPanel implements
71 AdjustmentListener, Printable, AlignmentViewPanel
73 public AlignViewport av;
75 ViewportRanges vpRanges;
77 OverviewPanel overviewPanel;
79 private SeqPanel seqPanel;
81 private IdPanel idPanel;
83 private boolean headless;
85 IdwidthAdjuster idwidthAdjuster;
88 public AlignFrame alignFrame;
90 private ScalePanel scalePanel;
92 private AnnotationPanel annotationPanel;
94 private AnnotationLabels alabels;
96 // this value is set false when selection area being dragged
97 boolean fastPaint = true;
99 private int hextent = 0;
101 private int vextent = 0;
104 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
105 * true, suppresses invoking the same method recursively.
107 private boolean dontScrollComplement;
109 private PropertyChangeListener propertyChangeListener;
111 private CalculationChooser calculationDialog;
114 * Creates a new AlignmentPanel object.
119 public AlignmentPanel(AlignFrame af, final AlignViewport av)
123 vpRanges = av.getRanges();
124 setSeqPanel(new SeqPanel(av, this));
125 setIdPanel(new IdPanel(av, this));
127 setScalePanel(new ScalePanel(av, this));
129 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
130 idwidthAdjuster = new IdwidthAdjuster(this);
131 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
133 setAnnotationPanel(new AnnotationPanel(this));
134 setAlabels(new AnnotationLabels(this));
136 annotationScroller.setViewportView(getAnnotationPanel());
137 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
139 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
140 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
142 setScrollValues(0, 0);
144 hscroll.addAdjustmentListener(this);
145 vscroll.addAdjustmentListener(this);
147 final AlignmentPanel ap = this;
148 propertyChangeListener = new PropertyChangeListener()
151 public void propertyChange(PropertyChangeEvent evt)
153 if (evt.getPropertyName().equals("alignment"))
155 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
160 av.addPropertyChangeListener(propertyChangeListener);
162 adjustAnnotationHeight();
167 public AlignViewportI getAlignViewport()
172 public void alignmentChanged()
174 av.alignmentChanged(this);
176 if (getCalculationDialog() != null)
178 getCalculationDialog().validateCalcTypes();
181 alignFrame.updateEditMenuBar();
183 paintAlignment(true);
190 public void fontChanged()
192 // set idCanvas bufferedImage to null
193 // to prevent drawing old image
194 FontMetrics fm = getFontMetrics(av.getFont());
196 scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
198 idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
199 .getCharHeight() + fm.getDescent()));
201 getIdPanel().getIdCanvas().gg = null;
202 getSeqPanel().seqCanvas.img = null;
203 getAnnotationPanel().adjustPanelHeight();
205 Dimension d = calculateIdWidth();
207 d.setSize(d.width + 4, d.height);
208 getIdPanel().getIdCanvas().setPreferredSize(d);
209 hscrollFillerPanel.setPreferredSize(d);
211 if (overviewPanel != null)
213 overviewPanel.setBoxPosition();
215 if (this.alignFrame.getSplitViewContainer() != null)
217 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
224 * Calculate the width of the alignment labels based on the displayed names
225 * and any bounds on label width set in preferences.
227 * @return Dimension giving the maximum width of the alignment label panel
228 * that should be used.
230 public Dimension calculateIdWidth()
232 // calculate sensible default width when no preference is available
234 if (av.getIdWidth() < 0)
236 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
237 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
238 r = calculateIdWidth(maxwidth);
239 av.setIdWidth(r.width);
244 r.width = av.getIdWidth();
251 * Calculate the width of the alignment labels based on the displayed names
252 * and any bounds on label width set in preferences.
255 * -1 or maximum width allowed for IdWidth
256 * @return Dimension giving the maximum width of the alignment label panel
257 * that should be used.
259 public Dimension calculateIdWidth(int maxwidth)
261 Container c = new Container();
263 FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
264 Font.ITALIC, av.font.getSize()));
266 AlignmentI al = av.getAlignment();
271 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
273 SequenceI s = al.getSequenceAt(i);
275 id = s.getDisplayId(av.getShowJVSuffix());
277 if (fm.stringWidth(id) > idWidth)
279 idWidth = fm.stringWidth(id);
285 // Also check annotation label widths
288 if (al.getAlignmentAnnotation() != null)
290 fm = c.getFontMetrics(getAlabels().getFont());
292 while (i < al.getAlignmentAnnotation().length)
294 String label = al.getAlignmentAnnotation()[i].label;
296 if (fm.stringWidth(label) > idWidth)
298 idWidth = fm.stringWidth(label);
305 return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
310 * Highlight the given results on the alignment.
313 public void highlightSearchResults(SearchResultsI results)
315 scrollToPosition(results);
316 getSeqPanel().seqCanvas.highlightSearchResults(results);
320 * Scroll the view to show the position of the highlighted region in results
321 * (if any) and redraw the overview
325 public boolean scrollToPosition(SearchResultsI results)
327 return scrollToPosition(results, 0, true, false);
331 * Scroll the view to show the position of the highlighted region in results
334 * @param searchResults
335 * @param redrawOverview
338 public boolean scrollToPosition(SearchResultsI searchResults,
339 boolean redrawOverview)
341 return scrollToPosition(searchResults, 0, redrawOverview, false);
345 * Scroll the view to show the position of the highlighted region in results
349 * @param verticalOffset
350 * if greater than zero, allows scrolling to a position below the
351 * first displayed sequence
352 * @param redrawOverview
353 * - when set, the overview will be recalculated (takes longer)
355 * if true, try to centre the search results horizontally in the view
356 * @return false if results were not found
358 public boolean scrollToPosition(SearchResultsI results,
359 int verticalOffset, boolean redrawOverview, boolean centre)
361 int startv, endv, starts, ends;
362 // TODO: properly locate search results in view when large numbers of hidden
363 // columns exist before highlighted region
364 // do we need to scroll the panel?
365 // TODO: tons of nullpointerexceptions raised here.
366 if (results != null && results.getSize() > 0 && av != null
367 && av.getAlignment() != null)
369 int seqIndex = av.getAlignment().findIndex(results);
374 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
376 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
384 // System.err.println(this.av.viewName + " Seq : " + seqIndex
385 // + " Scroll to " + start + "," + end);
388 * To centre results, scroll to positions half the visible width
389 * left/right of the start/end positions
393 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
394 start = Math.max(start - offset, 0);
395 end = end + offset - 1;
401 if (end == seq.getEnd())
405 if (av.hasHiddenColumns())
407 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
408 start = hidden.findColumnPosition(start);
409 end = hidden.findColumnPosition(end);
412 if (!hidden.isVisible(r[0]))
414 // don't scroll - position isn't visible
421 * allow for offset of target sequence (actually scroll to one above it)
423 seqIndex = Math.max(0, seqIndex - verticalOffset);
425 // System.out.println("start=" + start + ", end=" + end + ", startv="
426 // + av.getStartRes() + ", endv=" + av.getEndRes() + ", starts="
427 // + av.getStartSeq() + ", ends=" + av.getEndSeq());
428 if (!av.getWrapAlignment())
430 if ((startv = vpRanges.getStartRes()) >= start)
433 * Scroll left to make start of search results visible
435 // setScrollValues(start - 1, seqIndex); // plus one residue
436 setScrollValues(start, seqIndex);
438 else if ((endv = vpRanges.getEndRes()) <= end)
441 * Scroll right to make end of search results visible
443 // setScrollValues(startv + 1 + end - endv, seqIndex); // plus one
444 setScrollValues(startv + end - endv, seqIndex);
446 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
449 * Scroll up to make start of search results visible
451 setScrollValues(vpRanges.getStartRes(), seqIndex);
453 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
456 * Scroll down to make end of search results visible
458 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
462 * Else results are already visible - no need to scroll
467 scrollToWrappedVisible(start);
470 if (redrawOverview && overviewPanel != null)
472 overviewPanel.setBoxPosition();
474 paintAlignment(redrawOverview);
478 void scrollToWrappedVisible(int res)
480 int cwidth = getSeqPanel().seqCanvas
481 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
482 if (res < vpRanges.getStartRes()
483 || res >= (vpRanges.getStartRes() + cwidth))
485 vscroll.setValue((res / cwidth));
486 vpRanges.setStartRes(vscroll.getValue() * cwidth);
494 * @return DOCUMENT ME!
496 public OverviewPanel getOverviewPanel()
498 return overviewPanel;
507 public void setOverviewPanel(OverviewPanel op)
515 * Hide or show annotation panel
518 public void setAnnotationVisible(boolean b)
520 if (!av.getWrapAlignment())
522 annotationSpaceFillerHolder.setVisible(b);
523 annotationScroller.setVisible(b);
529 * automatically adjust annotation panel height for new annotation whilst
530 * ensuring the alignment is still visible.
533 public void adjustAnnotationHeight()
535 // TODO: display vertical annotation scrollbar if necessary
536 // this is called after loading new annotation onto alignment
537 if (alignFrame.getHeight() == 0)
539 System.out.println("NEEDS FIXING");
541 validateAnnotationDimensions(true);
543 paintAlignment(true);
547 * calculate the annotation dimensions and refresh slider values accordingly.
548 * need to do repaints/notifys afterwards.
550 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
552 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
554 if (adjustPanelHeight)
556 int rowHeight = av.getCharHeight();
557 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
560 * Estimate available height in the AlignFrame for alignment +
561 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
562 * hscroll, status bar (as these are not laid out we can't inspect their
563 * actual heights). Insets gives frame borders.
565 int stuff = Platform.isAMac() ? 80 : 100;
566 Insets insets = alignFrame.getInsets();
567 int availableHeight = alignFrame.getHeight() - stuff - insets.top
571 * If not enough vertical space, maximize annotation height while keeping
572 * at least two rows of alignment visible
574 if (annotationHeight + alignmentHeight > availableHeight)
576 annotationHeight = Math.min(annotationHeight, availableHeight - 2
582 // maintain same window layout whilst updating sliders
583 annotationHeight = annotationScroller.getSize().height;
587 annotationScroller.setPreferredSize(new Dimension(annotationScroller
588 .getWidth(), annotationHeight));
590 Dimension e = idPanel.getSize();
591 alabels.setSize(new Dimension(e.width, annotationHeight));
593 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
594 annotationSpaceFillerHolder.getWidth(), annotationHeight));
595 annotationScroller.validate();
596 annotationScroller.addNotify();
600 * update alignment layout for viewport settings
605 public void updateLayout()
608 setAnnotationVisible(av.isShowAnnotation());
609 boolean wrap = av.getWrapAlignment();
610 vpRanges.setStartSeq(0);
611 scalePanelHolder.setVisible(!wrap);
612 hscroll.setVisible(!wrap);
613 idwidthAdjuster.setVisible(!wrap);
617 annotationScroller.setVisible(false);
618 annotationSpaceFillerHolder.setVisible(false);
620 else if (av.isShowAnnotation())
622 annotationScroller.setVisible(true);
623 annotationSpaceFillerHolder.setVisible(true);
626 idSpaceFillerPanel1.setVisible(!wrap);
631 // return value is true if the scroll is valid
632 public boolean scrollUp(boolean up)
636 if (vscroll.getValue() < 1)
642 vscroll.setValue(vscroll.getValue() - 1);
646 if ((vextent + vscroll.getValue()) >= av.getAlignment().getHeight())
652 vscroll.setValue(vscroll.getValue() + 1);
666 * @return DOCUMENT ME!
668 public boolean scrollRight(boolean right)
672 if (hscroll.getValue() < 1)
678 hscroll.setValue(hscroll.getValue() - 1);
682 if ((hextent + hscroll.getValue()) >= av.getAlignment().getWidth())
688 hscroll.setValue(hscroll.getValue() + 1);
697 * Adjust row/column scrollers to show a visible position in the alignment.
700 * visible column to scroll to
702 * visible row to scroll to
705 public void setScrollValues(int x, int y)
707 if (av == null || av.getAlignment() == null)
711 int width = av.getAlignment().getWidth();
712 int height = av.getAlignment().getHeight();
714 if (av.hasHiddenColumns())
716 // reset the width to exclude hidden columns
717 width = av.getAlignment().getHiddenColumns()
718 .findColumnPosition(width);
721 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
722 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
729 if (vextent > height)
734 if ((hextent + x) > width)
739 if ((vextent + y) > height)
741 y = height - vextent;
754 // update endRes after x has (possibly) been adjusted
755 vpRanges.setEndRes((x + (getSeqPanel().seqCanvas.getWidth() / av
756 .getCharWidth())) - 1);
759 * each scroll adjustment triggers adjustmentValueChanged, which resets the
760 * 'do not scroll complement' flag; ensure it is the same for both
763 boolean flag = isDontScrollComplement();
764 hscroll.setValues(x, hextent, 0, width);
765 setDontScrollComplement(flag);
766 vscroll.setValues(y, vextent, 0, height);
776 public void adjustmentValueChanged(AdjustmentEvent evt)
778 int oldX = vpRanges.getStartRes();
779 int oldY = vpRanges.getStartSeq();
781 if (evt.getSource() == hscroll)
783 int x = hscroll.getValue();
784 vpRanges.setStartRes(x);
785 vpRanges.setEndRes((x + (getSeqPanel().seqCanvas.getWidth() / av
786 .getCharWidth())) - 1);
789 if (evt.getSource() == vscroll)
791 int offy = vscroll.getValue();
793 if (av.getWrapAlignment())
797 int rowSize = getSeqPanel().seqCanvas
798 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
799 vpRanges.setStartRes(offy * rowSize);
800 vpRanges.setEndRes((offy + 1) * rowSize);
804 // This is only called if file loaded is a jar file that
805 // was wrapped when saved and user has wrap alignment true
806 // as preference setting
807 SwingUtilities.invokeLater(new Runnable()
812 setScrollValues(vpRanges.getStartRes(),
813 vpRanges.getStartSeq());
820 vpRanges.setStartSeq(offy);
821 vpRanges.setEndSeq(offy
822 + (getSeqPanel().seqCanvas.getHeight() / av.getCharHeight())
827 if (overviewPanel != null)
829 overviewPanel.setBoxPosition();
832 int scrollX = vpRanges.getStartRes() - oldX;
833 int scrollY = vpRanges.getStartSeq() - oldY;
835 if (av.getWrapAlignment() || !fastPaint)
841 // Make sure we're not trying to draw a panel
842 // larger than the visible window
843 if (scrollX > vpRanges.getEndRes() - vpRanges.getStartRes())
845 scrollX = vpRanges.getEndRes() - vpRanges.getStartRes();
847 else if (scrollX < vpRanges.getStartRes() - vpRanges.getEndRes())
849 scrollX = vpRanges.getStartRes() - vpRanges.getEndRes();
852 if (scrollX != 0 || scrollY != 0)
854 getIdPanel().getIdCanvas().fastPaint(scrollY);
855 getSeqPanel().seqCanvas.fastPaint(scrollX, scrollY);
856 getScalePanel().repaint();
858 if (av.isShowAnnotation() && scrollX != 0)
860 getAnnotationPanel().fastPaint(scrollX);
865 * If there is one, scroll the (Protein/cDNA) complementary alignment to
866 * match, unless we are ourselves doing that.
868 if (isDontScrollComplement())
870 setDontScrollComplement(false);
874 av.scrollComplementaryAlignment();
879 * Repaint the alignment including the annotations and overview panels (if
883 public void paintAlignment(boolean updateOverview)
885 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
886 av.isShowAutocalculatedAbove());
887 sorter.sort(getAlignment().getAlignmentAnnotation(),
888 av.getSortAnnotationsBy());
893 // TODO: determine if this paintAlignment changed structure colours
894 av.getStructureSelectionManager().sequenceColoursChanged(this);
896 if (overviewPanel != null)
898 overviewPanel.updateOverviewImage();
910 public void paintComponent(Graphics g)
914 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
915 idPanelHolder.setPreferredSize(d);
916 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
920 * set scroll bar positions; first suppress this being 'followed' in any
921 * complementary split pane
923 setDontScrollComplement(true);
925 if (av.getWrapAlignment())
927 int maxwidth = av.getAlignment().getWidth();
929 if (av.hasHiddenColumns())
931 maxwidth = av.getAlignment().getHiddenColumns()
932 .findColumnPosition(maxwidth) - 1;
935 int canvasWidth = getSeqPanel().seqCanvas
936 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
940 / getSeqPanel().seqCanvas
941 .getWrappedCanvasWidth(getSeqPanel().seqCanvas
943 vscroll.setMaximum(max);
944 vscroll.setUnitIncrement(1);
945 vscroll.setVisibleAmount(1);
950 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
964 * @return DOCUMENT ME!
966 * @throws PrinterException
970 public int print(Graphics pg, PageFormat pf, int pi)
971 throws PrinterException
973 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
975 int pwidth = (int) pf.getImageableWidth();
976 int pheight = (int) pf.getImageableHeight();
978 if (av.getWrapAlignment())
980 return printWrappedAlignment(pwidth, pheight, pi, pg);
984 return printUnwrapped(pwidth, pheight, pi, pg, pg);
1000 * @return DOCUMENT ME!
1002 * @throws PrinterException
1006 * Draws the alignment image, including sequence ids, sequences, and
1007 * annotation labels and annotations if shown, on either one or two Graphics
1014 * the graphics context for sequence ids and annotation labels
1015 * @param alignmentGraphics
1016 * the graphics context for sequences and annotations (may or may not
1017 * be the same context as idGraphics)
1019 * @throws PrinterException
1021 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
1022 Graphics idGraphics, Graphics alignmentGraphics)
1023 throws PrinterException
1025 final int idWidth = getVisibleIdWidth(false);
1028 * Get the horizontal offset to where we draw the sequences.
1029 * This is idWidth if using a single Graphics context, else zero.
1031 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
1033 FontMetrics fm = getFontMetrics(av.getFont());
1034 int charHeight = av.getCharHeight();
1035 int scaleHeight = charHeight + fm.getDescent();
1037 idGraphics.setColor(Color.white);
1038 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1039 idGraphics.setFont(av.getFont());
1042 * How many sequences and residues can we fit on a printable page?
1044 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1046 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1048 int alignmentWidth = av.getAlignment().getWidth();
1049 int pagesWide = (alignmentWidth / totalRes) + 1;
1051 final int startRes = (pi % pagesWide) * totalRes;
1052 int endRes = (startRes + totalRes) - 1;
1054 if (endRes > (alignmentWidth - 1))
1056 endRes = alignmentWidth - 1;
1059 final int startSeq = (pi / pagesWide) * totalSeq;
1060 int endSeq = startSeq + totalSeq;
1062 int alignmentHeight = av.getAlignment().getHeight();
1063 if (endSeq > alignmentHeight)
1065 endSeq = alignmentHeight;
1068 int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1071 if (av.isShowAnnotation())
1073 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1076 pagesHigh /= pageHeight;
1078 if (pi >= (pagesWide * pagesHigh))
1080 return Printable.NO_SUCH_PAGE;
1082 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1086 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1088 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1089 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1090 pageWidth - idWidth, scaleHeight);
1091 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1094 * Draw the sequence ids, offset for scale height,
1095 * then reset to top left (0, 0)
1097 idGraphics.translate(0, scaleHeight);
1098 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1099 Color currentColor = null;
1100 Color currentTextColor = null;
1103 for (int i = startSeq; i < endSeq; i++)
1105 seq = av.getAlignment().getSequenceAt(i);
1106 if ((av.getSelectionGroup() != null)
1107 && av.getSelectionGroup().getSequences(null).contains(seq))
1110 * gray out ids of sequences in selection group (if any)
1112 currentColor = Color.gray;
1113 currentTextColor = Color.black;
1117 currentColor = av.getSequenceColour(seq);
1118 currentTextColor = Color.black;
1121 idGraphics.setColor(currentColor);
1122 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1125 idGraphics.setColor(currentTextColor);
1128 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1129 if (av.isRightAlignIds())
1131 fm = idGraphics.getFontMetrics();
1133 - fm.stringWidth(displayId)
1137 idGraphics.drawString(displayId, xPos,
1138 (((i - startSeq) * charHeight) + charHeight)
1139 - (charHeight / 5));
1141 idGraphics.setFont(av.getFont());
1142 idGraphics.translate(0, -scaleHeight);
1145 * draw the sequences, offset for scale height, and id width (if using a
1146 * single graphics context), then reset to (0, scale height)
1148 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1149 getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1150 startSeq, endSeq, 0);
1151 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1153 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1156 * draw annotation labels; drawComponent() translates by
1157 * getScrollOffset(), so compensate for that first;
1158 * then reset to (0, scale height)
1160 int offset = getAlabels().getScrollOffset();
1161 idGraphics.translate(0, -offset);
1162 idGraphics.translate(0, alignmentDrawnHeight);
1163 getAlabels().drawComponent(idGraphics, idWidth);
1164 idGraphics.translate(0, -alignmentDrawnHeight);
1167 * draw the annotations starting at
1168 * (idOffset, alignmentHeight) from (0, scaleHeight)
1170 alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1171 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1172 alignmentGraphics, -1, startRes, endRes + 1);
1175 return Printable.PAGE_EXISTS;
1190 * @return DOCUMENT ME!
1192 * @throws PrinterException
1195 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1196 Graphics pg) throws PrinterException
1198 int annotationHeight = 0;
1199 AnnotationLabels labels = null;
1200 if (av.isShowAnnotation())
1202 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1203 labels = new AnnotationLabels(av);
1206 int hgap = av.getCharHeight();
1207 if (av.getScaleAboveWrapped())
1209 hgap += av.getCharHeight();
1212 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1215 int idWidth = getVisibleIdWidth(false);
1217 int maxwidth = av.getAlignment().getWidth();
1218 if (av.hasHiddenColumns())
1220 maxwidth = av.getAlignment().getHiddenColumns()
1221 .findColumnPosition(maxwidth) - 1;
1224 int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1227 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1229 pg.setColor(Color.white);
1230 pg.fillRect(0, 0, pwidth, pheight);
1231 pg.setFont(av.getFont());
1235 pg.setColor(Color.black);
1237 pg.translate(0, -pi * pheight);
1239 pg.setClip(0, pi * pheight, pwidth, pheight);
1245 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1247 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1248 SequenceI s = av.getAlignment().getSequenceAt(i);
1249 String string = s.getDisplayId(av.getShowJVSuffix());
1251 if (av.isRightAlignIds())
1253 FontMetrics fm = pg.getFontMetrics();
1254 xPos = idWidth - fm.stringWidth(string) - 4;
1256 pg.drawString(string, xPos,
1257 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1258 - (av.getCharHeight() / 5));
1263 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1265 pg.setFont(av.getFont());
1266 labels.drawComponent(pg, idWidth);
1270 - (av.getAlignment().getHeight() * av
1275 } while (ypos < totalHeight);
1277 pg.translate(idWidth, 0);
1279 getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1282 if ((pi * pheight) < totalHeight)
1284 return Printable.PAGE_EXISTS;
1289 return Printable.NO_SUCH_PAGE;
1294 * get current sequence ID panel width, or nominal value if panel were to be
1295 * displayed using default settings
1299 public int getVisibleIdWidth()
1301 return getVisibleIdWidth(true);
1305 * get current sequence ID panel width, or nominal value if panel were to be
1306 * displayed using default settings
1309 * indicate if the Id width for onscreen or offscreen display should
1313 public int getVisibleIdWidth(boolean onscreen)
1315 // see if rendering offscreen - check preferences and calc width accordingly
1316 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1318 return calculateIdWidth(-1).width + 4;
1320 Integer idwidth = null;
1322 || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1324 int w = getIdPanel().getWidth();
1325 return (w > 0 ? w : calculateIdWidth().width + 4);
1327 return idwidth.intValue() + 4;
1330 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1332 int boarderBottomOffset = 5;
1333 long pSessionId = System.currentTimeMillis();
1334 headless = (System.getProperty("java.awt.headless") != null && System
1335 .getProperty("java.awt.headless").equals("true"));
1336 if (alignFrame != null && !headless)
1340 alignFrame.setProgressBar(MessageManager.formatMessage(
1341 "status.saving_file", new Object[] { type.getLabel() }),
1347 AlignmentDimension aDimension = getAlignmentDimension();
1350 jalview.util.ImageMaker im;
1351 final String imageAction, imageTitle;
1352 if (type == jalview.util.ImageMaker.TYPE.PNG)
1354 imageAction = "Create PNG image from alignment";
1357 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1359 imageAction = "Create EPS file from alignment";
1360 imageTitle = alignFrame.getTitle();
1364 imageAction = "Create SVG file from alignment";
1365 imageTitle = alignFrame.getTitle();
1368 im = new jalview.util.ImageMaker(this, type, imageAction,
1369 aDimension.getWidth(), aDimension.getHeight()
1370 + boarderBottomOffset, file, imageTitle,
1371 alignFrame, pSessionId, headless);
1372 Graphics graphics = im.getGraphics();
1373 if (av.getWrapAlignment())
1375 if (graphics != null)
1377 printWrappedAlignment(aDimension.getWidth(),
1378 aDimension.getHeight() + boarderBottomOffset, 0,
1385 if (graphics != null)
1387 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1388 0, graphics, graphics);
1393 } catch (OutOfMemoryError err)
1396 System.out.println("########################\n" + "OUT OF MEMORY "
1397 + file + "\n" + "########################");
1398 new OOMWarning("Creating Image for " + file, err);
1399 // System.out.println("Create IMAGE: " + err);
1400 } catch (Exception ex)
1402 ex.printStackTrace();
1410 public AlignmentDimension getAlignmentDimension()
1412 int maxwidth = av.getAlignment().getWidth();
1413 if (av.hasHiddenColumns())
1415 maxwidth = av.getAlignment().getHiddenColumns()
1416 .findColumnPosition(maxwidth);
1419 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1420 + getScalePanel().getHeight();
1421 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1423 if (av.getWrapAlignment())
1425 height = getWrappedHeight();
1428 // need to obtain default alignment width and then add in any
1429 // additional allowance for id margin
1430 // this duplicates the calculation in getWrappedHeight but adjusts for
1432 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1433 - alignFrame.getInsets().left
1434 - alignFrame.getInsets().right - getVisibleIdWidth()
1435 + getVisibleIdWidth(false);
1439 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1443 else if (av.isShowAnnotation())
1445 height += getAnnotationPanel().adjustPanelHeight() + 3;
1447 return new AlignmentDimension(width, height);
1454 public void makeEPS(File epsFile)
1456 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1462 public void makePNG(File pngFile)
1464 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1467 public void makeSVG(File svgFile)
1469 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1472 public void makePNGImageMap(File imgMapFile, String imageName)
1474 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1475 // ////////////////////////////////////////////
1476 int idWidth = getVisibleIdWidth(false);
1477 FontMetrics fm = getFontMetrics(av.getFont());
1478 int scaleHeight = av.getCharHeight() + fm.getDescent();
1481 // ////////////////////////////////
1482 if (imgMapFile != null)
1486 int s, sSize = av.getAlignment().getHeight(), res, alwidth = av
1487 .getAlignment().getWidth(), g, gSize, f, fSize, sy;
1488 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1489 out.println(jalview.io.HTMLOutput.getImageMapHTML());
1490 out.println("<img src=\"" + imageName
1491 + "\" border=\"0\" usemap=\"#Map\" >"
1492 + "<map name=\"Map\">");
1494 for (s = 0; s < sSize; s++)
1496 sy = s * av.getCharHeight() + scaleHeight;
1498 SequenceI seq = av.getAlignment().getSequenceAt(s);
1499 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1500 for (res = 0; res < alwidth; res++)
1502 StringBuilder text = new StringBuilder(512);
1503 String triplet = null;
1504 if (av.getAlignment().isNucleotide())
1506 triplet = ResidueProperties.nucleotideName.get(seq
1507 .getCharAt(res) + "");
1511 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(res)
1515 if (triplet == null)
1520 int seqPos = seq.findPosition(res);
1521 gSize = groups.length;
1522 for (g = 0; g < gSize; g++)
1524 if (text.length() < 1)
1526 text.append("<area shape=\"rect\" coords=\"")
1527 .append((idWidth + res * av.getCharWidth()))
1528 .append(",").append(sy).append(",")
1529 .append((idWidth + (res + 1) * av.getCharWidth()))
1530 .append(",").append((av.getCharHeight() + sy))
1531 .append("\"").append(" onMouseOver=\"toolTip('")
1532 .append(seqPos).append(" ").append(triplet);
1535 if (groups[g].getStartRes() < res
1536 && groups[g].getEndRes() > res)
1538 text.append("<br><em>").append(groups[g].getName())
1543 if (text.length() < 1)
1545 text.append("<area shape=\"rect\" coords=\"")
1546 .append((idWidth + res * av.getCharWidth()))
1547 .append(",").append(sy).append(",")
1548 .append((idWidth + (res + 1) * av.getCharWidth()))
1549 .append(",").append((av.getCharHeight() + sy))
1550 .append("\"").append(" onMouseOver=\"toolTip('")
1551 .append(seqPos).append(" ").append(triplet);
1553 if (!Comparison.isGap(seq.getCharAt(res)))
1555 List<SequenceFeature> features = seq.getFeatures()
1556 .findFeatures(seqPos, seqPos);
1557 for (SequenceFeature sf : features)
1559 if (sf.isContactFeature())
1561 text.append("<br>").append(sf.getType()).append(" ")
1562 .append(sf.getBegin()).append(":")
1563 .append(sf.getEnd());
1567 text.append("<br>");
1568 text.append(sf.getType());
1569 String description = sf.getDescription();
1570 if (description != null
1571 && !sf.getType().equals(description))
1573 description = description.replace("\"", """);
1574 text.append(" ").append(description);
1577 String status = sf.getStatus();
1578 if (status != null && !"".equals(status))
1580 text.append(" (").append(status).append(")");
1583 if (text.length() > 1)
1585 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1586 out.println(text.toString());
1591 out.println("</map></body></html>");
1594 } catch (Exception ex)
1596 ex.printStackTrace();
1598 } // /////////END OF IMAGE MAP
1602 int getWrappedHeight()
1604 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1606 if (System.getProperty("java.awt.headless") != null
1607 && System.getProperty("java.awt.headless").equals("true"))
1609 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1610 - vscroll.getPreferredSize().width
1611 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1614 int chunkWidth = getSeqPanel().seqCanvas
1615 .getWrappedCanvasWidth(seqPanelWidth);
1617 int hgap = av.getCharHeight();
1618 if (av.getScaleAboveWrapped())
1620 hgap += av.getCharHeight();
1623 int annotationHeight = 0;
1624 if (av.isShowAnnotation())
1626 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1629 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1632 int maxwidth = av.getAlignment().getWidth();
1633 if (av.hasHiddenColumns())
1635 maxwidth = av.getAlignment().getHiddenColumns()
1636 .findColumnPosition(maxwidth) - 1;
1639 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1645 * close the panel - deregisters all listeners and nulls any references to
1648 public void closePanel()
1650 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1651 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1652 PaintRefresher.RemoveComponent(this);
1657 * try to ensure references are nulled
1659 if (annotationPanel != null)
1661 annotationPanel.dispose();
1666 av.removePropertyChangeListener(propertyChangeListener);
1667 jalview.structure.StructureSelectionManager ssm = av
1668 .getStructureSelectionManager();
1669 ssm.removeStructureViewerListener(getSeqPanel(), null);
1670 ssm.removeSelectionListener(getSeqPanel());
1671 ssm.removeCommandListener(av);
1672 ssm.removeStructureViewerListener(getSeqPanel(), null);
1673 ssm.removeSelectionListener(getSeqPanel());
1679 if (Cache.log.isDebugEnabled())
1681 Cache.log.warn("Closing alignment panel which is already closed.");
1687 * Close any open dialogs that would be orphaned when this one is closed
1689 protected void closeChildFrames()
1691 if (calculationDialog != null)
1693 calculationDialog.closeFrame();
1698 * hides or shows dynamic annotation rows based on groups and av state flags
1700 public void updateAnnotation()
1702 updateAnnotation(false, false);
1705 public void updateAnnotation(boolean applyGlobalSettings)
1707 updateAnnotation(applyGlobalSettings, false);
1710 public void updateAnnotation(boolean applyGlobalSettings,
1711 boolean preserveNewGroupSettings)
1713 av.updateGroupAnnotationSettings(applyGlobalSettings,
1714 preserveNewGroupSettings);
1715 adjustAnnotationHeight();
1719 public AlignmentI getAlignment()
1721 return av == null ? null : av.getAlignment();
1725 public String getViewName()
1731 * Make/Unmake this alignment panel the current input focus
1735 public void setSelected(boolean b)
1739 if (alignFrame.getSplitViewContainer() != null)
1742 * bring enclosing SplitFrame to front first if there is one
1744 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1746 alignFrame.setSelected(b);
1747 } catch (Exception ex)
1753 alignFrame.setDisplayedView(this);
1758 public StructureSelectionManager getStructureSelectionManager()
1760 return av.getStructureSelectionManager();
1764 public void raiseOOMWarning(String string, OutOfMemoryError error)
1766 new OOMWarning(string, error, this);
1770 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1773 return new FeatureRenderer(this);
1777 public jalview.api.FeatureRenderer getFeatureRenderer()
1779 return seqPanel.seqCanvas.getFeatureRenderer();
1782 public void updateFeatureRenderer(
1783 jalview.renderer.seqfeatures.FeatureRenderer fr)
1785 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1788 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1790 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1792 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1796 public ScalePanel getScalePanel()
1801 public void setScalePanel(ScalePanel scalePanel)
1803 this.scalePanel = scalePanel;
1806 public SeqPanel getSeqPanel()
1811 public void setSeqPanel(SeqPanel seqPanel)
1813 this.seqPanel = seqPanel;
1816 public AnnotationPanel getAnnotationPanel()
1818 return annotationPanel;
1821 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1823 this.annotationPanel = annotationPanel;
1826 public AnnotationLabels getAlabels()
1831 public void setAlabels(AnnotationLabels alabels)
1833 this.alabels = alabels;
1836 public IdPanel getIdPanel()
1841 public void setIdPanel(IdPanel idPanel)
1843 this.idPanel = idPanel;
1847 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1848 * The aim is to keep the two alignments 'lined up' on their centre columns.
1851 * holds mapped region(s) of this alignment that we are scrolling
1852 * 'to'; may be modified for sequence offset by this method
1853 * @param verticalOffset
1854 * the number of visible sequences to show above the mapped region
1856 public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1859 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1860 * mapped), we can make the scroll-to location a sequence above the one
1863 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1864 List<SequenceI> seqs = av.getAlignment().getSequences();
1867 * This is like AlignmentI.findIndex(seq) but here we are matching the
1868 * dataset sequence not the aligned sequence
1870 boolean matched = false;
1871 for (SequenceI seq : seqs)
1873 if (mappedTo == seq.getDatasetSequence())
1881 return; // failsafe, shouldn't happen
1885 * Scroll to position but centring the target residue.
1887 scrollToPosition(sr, verticalOffset, true, true);
1891 * Set a flag to say do not scroll any (cDNA/protein) complement.
1895 protected void setDontScrollComplement(boolean b)
1897 this.dontScrollComplement = b;
1900 protected boolean isDontScrollComplement()
1902 return this.dontScrollComplement;
1908 * @adjustHeight if true, try to recalculate panel height for visible
1911 protected void refresh(boolean adjustHeight)
1913 validateAnnotationDimensions(adjustHeight);
1917 // sort, repaint, update overview
1918 paintAlignment(true);
1922 // lightweight repaint
1928 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1929 * reference should be nulled when the dialog is closed.
1931 * @param calculationChooser
1933 public void setCalculationDialog(CalculationChooser calculationChooser)
1935 calculationDialog = calculationChooser;
1939 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1942 public CalculationChooser getCalculationDialog()
1944 return calculationDialog;