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.MessageManager;
38 import jalview.util.Platform;
39 import jalview.viewmodel.ViewportRanges;
41 import java.awt.BorderLayout;
42 import java.awt.Color;
43 import java.awt.Container;
44 import java.awt.Dimension;
46 import java.awt.FontMetrics;
47 import java.awt.Graphics;
48 import java.awt.Insets;
49 import java.awt.event.AdjustmentEvent;
50 import java.awt.event.AdjustmentListener;
51 import java.awt.print.PageFormat;
52 import java.awt.print.Printable;
53 import java.awt.print.PrinterException;
54 import java.beans.PropertyChangeEvent;
55 import java.beans.PropertyChangeListener;
57 import java.io.FileWriter;
58 import java.io.PrintWriter;
59 import java.util.List;
61 import javax.swing.SwingUtilities;
67 * @version $Revision: 1.161 $
69 public class AlignmentPanel extends GAlignmentPanel implements
70 AdjustmentListener, Printable, AlignmentViewPanel
72 public AlignViewport av;
74 ViewportRanges vpRanges;
76 OverviewPanel overviewPanel;
78 private SeqPanel seqPanel;
80 private IdPanel idPanel;
82 private boolean headless;
84 IdwidthAdjuster idwidthAdjuster;
87 public AlignFrame alignFrame;
89 private ScalePanel scalePanel;
91 private AnnotationPanel annotationPanel;
93 private AnnotationLabels alabels;
95 // this value is set false when selection area being dragged
96 boolean fastPaint = true;
98 private int hextent = 0;
100 private int vextent = 0;
103 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
104 * true, suppresses invoking the same method recursively.
106 private boolean dontScrollComplement;
108 private PropertyChangeListener propertyChangeListener;
110 private CalculationChooser calculationDialog;
113 * Creates a new AlignmentPanel object.
118 public AlignmentPanel(AlignFrame af, final AlignViewport av)
122 vpRanges = av.getRanges();
123 setSeqPanel(new SeqPanel(av, this));
124 setIdPanel(new IdPanel(av, this));
126 setScalePanel(new ScalePanel(av, this));
128 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
129 idwidthAdjuster = new IdwidthAdjuster(this);
130 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
132 setAnnotationPanel(new AnnotationPanel(this));
133 setAlabels(new AnnotationLabels(this));
135 annotationScroller.setViewportView(getAnnotationPanel());
136 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
138 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
139 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
141 setScrollValues(0, 0);
143 hscroll.addAdjustmentListener(this);
144 vscroll.addAdjustmentListener(this);
146 final AlignmentPanel ap = this;
147 propertyChangeListener = new PropertyChangeListener()
150 public void propertyChange(PropertyChangeEvent evt)
152 if (evt.getPropertyName().equals("alignment"))
154 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
159 av.addPropertyChangeListener(propertyChangeListener);
161 adjustAnnotationHeight();
166 public AlignViewportI getAlignViewport()
171 public void alignmentChanged()
173 av.alignmentChanged(this);
175 if (getCalculationDialog() != null)
177 getCalculationDialog().validateCalcTypes();
180 alignFrame.updateEditMenuBar();
182 paintAlignment(true);
189 public void fontChanged()
191 // set idCanvas bufferedImage to null
192 // to prevent drawing old image
193 FontMetrics fm = getFontMetrics(av.getFont());
195 scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
197 idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
198 .getCharHeight() + fm.getDescent()));
200 getIdPanel().getIdCanvas().gg = null;
201 getSeqPanel().seqCanvas.img = null;
202 getAnnotationPanel().adjustPanelHeight();
204 Dimension d = calculateIdWidth();
206 d.setSize(d.width + 4, d.height);
207 getIdPanel().getIdCanvas().setPreferredSize(d);
208 hscrollFillerPanel.setPreferredSize(d);
210 if (overviewPanel != null)
212 overviewPanel.setBoxPosition();
214 if (this.alignFrame.getSplitViewContainer() != null)
216 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
223 * Calculate the width of the alignment labels based on the displayed names
224 * and any bounds on label width set in preferences.
226 * @return Dimension giving the maximum width of the alignment label panel
227 * that should be used.
229 public Dimension calculateIdWidth()
231 // calculate sensible default width when no preference is available
233 if (av.getIdWidth() < 0)
235 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
236 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
237 r = calculateIdWidth(maxwidth);
238 av.setIdWidth(r.width);
243 r.width = av.getIdWidth();
250 * Calculate the width of the alignment labels based on the displayed names
251 * and any bounds on label width set in preferences.
254 * -1 or maximum width allowed for IdWidth
255 * @return Dimension giving the maximum width of the alignment label panel
256 * that should be used.
258 public Dimension calculateIdWidth(int maxwidth)
260 Container c = new Container();
262 FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
263 Font.ITALIC, av.font.getSize()));
265 AlignmentI al = av.getAlignment();
270 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
272 SequenceI s = al.getSequenceAt(i);
274 id = s.getDisplayId(av.getShowJVSuffix());
276 if (fm.stringWidth(id) > idWidth)
278 idWidth = fm.stringWidth(id);
284 // Also check annotation label widths
287 if (al.getAlignmentAnnotation() != null)
289 fm = c.getFontMetrics(getAlabels().getFont());
291 while (i < al.getAlignmentAnnotation().length)
293 String label = al.getAlignmentAnnotation()[i].label;
295 if (fm.stringWidth(label) > idWidth)
297 idWidth = fm.stringWidth(label);
304 return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
309 * Highlight the given results on the alignment.
312 public void highlightSearchResults(SearchResultsI results)
314 scrollToPosition(results);
315 getSeqPanel().seqCanvas.highlightSearchResults(results);
319 * Scroll the view to show the position of the highlighted region in results
320 * (if any) and redraw the overview
324 public boolean scrollToPosition(SearchResultsI results)
326 return scrollToPosition(results, 0, true, false);
330 * Scroll the view to show the position of the highlighted region in results
333 * @param searchResults
334 * @param redrawOverview
337 public boolean scrollToPosition(SearchResultsI searchResults,
338 boolean redrawOverview)
340 return scrollToPosition(searchResults, 0, redrawOverview, false);
344 * Scroll the view to show the position of the highlighted region in results
348 * @param verticalOffset
349 * if greater than zero, allows scrolling to a position below the
350 * first displayed sequence
351 * @param redrawOverview
352 * - when set, the overview will be recalculated (takes longer)
354 * if true, try to centre the search results horizontally in the view
355 * @return false if results were not found
357 public boolean scrollToPosition(SearchResultsI results,
358 int verticalOffset, boolean redrawOverview, boolean centre)
360 int startv, endv, starts, ends;
361 // TODO: properly locate search results in view when large numbers of hidden
362 // columns exist before highlighted region
363 // do we need to scroll the panel?
364 // TODO: tons of nullpointerexceptions raised here.
365 if (results != null && results.getSize() > 0 && av != null
366 && av.getAlignment() != null)
368 int seqIndex = av.getAlignment().findIndex(results);
373 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
375 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
383 // System.err.println(this.av.viewName + " Seq : " + seqIndex
384 // + " Scroll to " + start + "," + end);
387 * To centre results, scroll to positions half the visible width
388 * left/right of the start/end positions
392 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
393 start = Math.max(start - offset, 0);
394 end = end + offset - 1;
400 if (end == seq.getEnd())
404 if (av.hasHiddenColumns())
406 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
407 start = hidden.findColumnPosition(start);
408 end = hidden.findColumnPosition(end);
411 if (!hidden.isVisible(r[0]))
413 // don't scroll - position isn't visible
420 * allow for offset of target sequence (actually scroll to one above it)
422 seqIndex = Math.max(0, seqIndex - verticalOffset);
424 // System.out.println("start=" + start + ", end=" + end + ", startv="
425 // + av.getStartRes() + ", endv=" + av.getEndRes() + ", starts="
426 // + av.getStartSeq() + ", ends=" + av.getEndSeq());
427 if (!av.getWrapAlignment())
429 if ((startv = vpRanges.getStartRes()) >= start)
432 * Scroll left to make start of search results visible
434 // setScrollValues(start - 1, seqIndex); // plus one residue
435 setScrollValues(start, seqIndex);
437 else if ((endv = vpRanges.getEndRes()) <= end)
440 * Scroll right to make end of search results visible
442 // setScrollValues(startv + 1 + end - endv, seqIndex); // plus one
443 setScrollValues(startv + end - endv, seqIndex);
445 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
448 * Scroll up to make start of search results visible
450 setScrollValues(vpRanges.getStartRes(), seqIndex);
452 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
455 * Scroll down to make end of search results visible
457 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
461 * Else results are already visible - no need to scroll
466 scrollToWrappedVisible(start);
469 if (redrawOverview && overviewPanel != null)
471 overviewPanel.setBoxPosition();
473 paintAlignment(redrawOverview);
477 void scrollToWrappedVisible(int res)
479 int cwidth = getSeqPanel().seqCanvas
480 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
481 if (res < vpRanges.getStartRes()
482 || res >= (vpRanges.getStartRes() + cwidth))
484 vscroll.setValue((res / cwidth));
485 vpRanges.setStartRes(vscroll.getValue() * cwidth);
493 * @return DOCUMENT ME!
495 public OverviewPanel getOverviewPanel()
497 return overviewPanel;
506 public void setOverviewPanel(OverviewPanel op)
514 * Hide or show annotation panel
517 public void setAnnotationVisible(boolean b)
519 if (!av.getWrapAlignment())
521 annotationSpaceFillerHolder.setVisible(b);
522 annotationScroller.setVisible(b);
528 * automatically adjust annotation panel height for new annotation whilst
529 * ensuring the alignment is still visible.
532 public void adjustAnnotationHeight()
534 // TODO: display vertical annotation scrollbar if necessary
535 // this is called after loading new annotation onto alignment
536 if (alignFrame.getHeight() == 0)
538 System.out.println("NEEDS FIXING");
540 validateAnnotationDimensions(true);
542 paintAlignment(true);
546 * calculate the annotation dimensions and refresh slider values accordingly.
547 * need to do repaints/notifys afterwards.
549 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
551 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
553 if (adjustPanelHeight)
555 int rowHeight = av.getCharHeight();
556 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
559 * Estimate available height in the AlignFrame for alignment +
560 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
561 * hscroll, status bar (as these are not laid out we can't inspect their
562 * actual heights). Insets gives frame borders.
564 int stuff = Platform.isAMac() ? 80 : 100;
565 Insets insets = alignFrame.getInsets();
566 int availableHeight = alignFrame.getHeight() - stuff - insets.top
570 * If not enough vertical space, maximize annotation height while keeping
571 * at least two rows of alignment visible
573 if (annotationHeight + alignmentHeight > availableHeight)
575 annotationHeight = Math.min(annotationHeight, availableHeight - 2
581 // maintain same window layout whilst updating sliders
582 annotationHeight = annotationScroller.getSize().height;
586 annotationScroller.setPreferredSize(new Dimension(annotationScroller
587 .getWidth(), annotationHeight));
589 Dimension e = idPanel.getSize();
590 alabels.setSize(new Dimension(e.width, annotationHeight));
592 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
593 annotationSpaceFillerHolder.getWidth(), annotationHeight));
594 annotationScroller.validate();
595 annotationScroller.addNotify();
599 * update alignment layout for viewport settings
604 public void updateLayout()
607 setAnnotationVisible(av.isShowAnnotation());
608 boolean wrap = av.getWrapAlignment();
609 vpRanges.setStartSeq(0);
610 scalePanelHolder.setVisible(!wrap);
611 hscroll.setVisible(!wrap);
612 idwidthAdjuster.setVisible(!wrap);
616 annotationScroller.setVisible(false);
617 annotationSpaceFillerHolder.setVisible(false);
619 else if (av.isShowAnnotation())
621 annotationScroller.setVisible(true);
622 annotationSpaceFillerHolder.setVisible(true);
625 idSpaceFillerPanel1.setVisible(!wrap);
630 // return value is true if the scroll is valid
631 public boolean scrollUp(boolean up)
635 if (vscroll.getValue() < 1)
641 vscroll.setValue(vscroll.getValue() - 1);
645 if ((vextent + vscroll.getValue()) >= av.getAlignment().getHeight())
651 vscroll.setValue(vscroll.getValue() + 1);
665 * @return DOCUMENT ME!
667 public boolean scrollRight(boolean right)
671 if (hscroll.getValue() < 1)
677 hscroll.setValue(hscroll.getValue() - 1);
681 if ((hextent + hscroll.getValue()) >= av.getAlignment().getWidth())
687 hscroll.setValue(hscroll.getValue() + 1);
696 * Adjust row/column scrollers to show a visible position in the alignment.
699 * visible column to scroll to
701 * visible row to scroll to
704 public void setScrollValues(int x, int y)
706 if (av == null || av.getAlignment() == null)
710 int width = av.getAlignment().getWidth();
711 int height = av.getAlignment().getHeight();
713 if (av.hasHiddenColumns())
715 // reset the width to exclude hidden columns
716 width = av.getAlignment().getHiddenColumns()
717 .findColumnPosition(width);
720 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
721 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
728 if (vextent > height)
733 if ((hextent + x) > width)
738 if ((vextent + y) > height)
740 y = height - vextent;
753 // update endRes after x has (possibly) been adjusted
754 vpRanges.setEndRes((x + (getSeqPanel().seqCanvas.getWidth() / av
755 .getCharWidth())) - 1);
758 * each scroll adjustment triggers adjustmentValueChanged, which resets the
759 * 'do not scroll complement' flag; ensure it is the same for both
762 boolean flag = isDontScrollComplement();
763 hscroll.setValues(x, hextent, 0, width);
764 setDontScrollComplement(flag);
765 vscroll.setValues(y, vextent, 0, height);
775 public void adjustmentValueChanged(AdjustmentEvent evt)
777 int oldX = vpRanges.getStartRes();
778 int oldY = vpRanges.getStartSeq();
780 if (evt.getSource() == hscroll)
782 int x = hscroll.getValue();
783 vpRanges.setStartRes(x);
784 vpRanges.setEndRes((x + (getSeqPanel().seqCanvas.getWidth() / av
785 .getCharWidth())) - 1);
788 if (evt.getSource() == vscroll)
790 int offy = vscroll.getValue();
792 if (av.getWrapAlignment())
796 int rowSize = getSeqPanel().seqCanvas
797 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
798 vpRanges.setStartRes(offy * rowSize);
799 vpRanges.setEndRes((offy + 1) * rowSize);
803 // This is only called if file loaded is a jar file that
804 // was wrapped when saved and user has wrap alignment true
805 // as preference setting
806 SwingUtilities.invokeLater(new Runnable()
811 setScrollValues(vpRanges.getStartRes(),
812 vpRanges.getStartSeq());
819 vpRanges.setStartSeq(offy);
820 vpRanges.setEndSeq(offy
821 + (getSeqPanel().seqCanvas.getHeight() / av.getCharHeight())
826 if (overviewPanel != null)
828 overviewPanel.setBoxPosition();
831 int scrollX = vpRanges.getStartRes() - oldX;
832 int scrollY = vpRanges.getStartSeq() - oldY;
834 if (av.getWrapAlignment() || !fastPaint)
840 // Make sure we're not trying to draw a panel
841 // larger than the visible window
842 if (scrollX > vpRanges.getEndRes() - vpRanges.getStartRes())
844 scrollX = vpRanges.getEndRes() - vpRanges.getStartRes();
846 else if (scrollX < vpRanges.getStartRes() - vpRanges.getEndRes())
848 scrollX = vpRanges.getStartRes() - vpRanges.getEndRes();
851 if (scrollX != 0 || scrollY != 0)
853 getIdPanel().getIdCanvas().fastPaint(scrollY);
854 getSeqPanel().seqCanvas.fastPaint(scrollX, scrollY);
855 getScalePanel().repaint();
857 if (av.isShowAnnotation() && scrollX != 0)
859 getAnnotationPanel().fastPaint(scrollX);
864 * If there is one, scroll the (Protein/cDNA) complementary alignment to
865 * match, unless we are ourselves doing that.
867 if (isDontScrollComplement())
869 setDontScrollComplement(false);
873 av.scrollComplementaryAlignment();
878 * Repaint the alignment including the annotations and overview panels (if
882 public void paintAlignment(boolean updateOverview)
884 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
885 av.isShowAutocalculatedAbove());
886 sorter.sort(getAlignment().getAlignmentAnnotation(),
887 av.getSortAnnotationsBy());
892 // TODO: determine if this paintAlignment changed structure colours
893 av.getStructureSelectionManager().sequenceColoursChanged(this);
895 if (overviewPanel != null)
897 overviewPanel.updateOverviewImage();
909 public void paintComponent(Graphics g)
913 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
914 idPanelHolder.setPreferredSize(d);
915 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
919 * set scroll bar positions; first suppress this being 'followed' in any
920 * complementary split pane
922 setDontScrollComplement(true);
924 if (av.getWrapAlignment())
926 int maxwidth = av.getAlignment().getWidth();
928 if (av.hasHiddenColumns())
930 maxwidth = av.getAlignment().getHiddenColumns()
931 .findColumnPosition(maxwidth) - 1;
934 int canvasWidth = getSeqPanel().seqCanvas
935 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
939 / getSeqPanel().seqCanvas
940 .getWrappedCanvasWidth(getSeqPanel().seqCanvas
942 vscroll.setMaximum(max);
943 vscroll.setUnitIncrement(1);
944 vscroll.setVisibleAmount(1);
949 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
963 * @return DOCUMENT ME!
965 * @throws PrinterException
969 public int print(Graphics pg, PageFormat pf, int pi)
970 throws PrinterException
972 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
974 int pwidth = (int) pf.getImageableWidth();
975 int pheight = (int) pf.getImageableHeight();
977 if (av.getWrapAlignment())
979 return printWrappedAlignment(pwidth, pheight, pi, pg);
983 return printUnwrapped(pwidth, pheight, pi, pg, pg);
999 * @return DOCUMENT ME!
1001 * @throws PrinterException
1005 * Draws the alignment image, including sequence ids, sequences, and
1006 * annotation labels and annotations if shown, on either one or two Graphics
1013 * the graphics context for sequence ids and annotation labels
1014 * @param alignmentGraphics
1015 * the graphics context for sequences and annotations (may or may not
1016 * be the same context as idGraphics)
1018 * @throws PrinterException
1020 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
1021 Graphics idGraphics, Graphics alignmentGraphics)
1022 throws PrinterException
1024 final int idWidth = getVisibleIdWidth(false);
1027 * Get the horizontal offset to where we draw the sequences.
1028 * This is idWidth if using a single Graphics context, else zero.
1030 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
1032 FontMetrics fm = getFontMetrics(av.getFont());
1033 int charHeight = av.getCharHeight();
1034 int scaleHeight = charHeight + fm.getDescent();
1036 idGraphics.setColor(Color.white);
1037 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1038 idGraphics.setFont(av.getFont());
1041 * How many sequences and residues can we fit on a printable page?
1043 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1045 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1047 int alignmentWidth = av.getAlignment().getWidth();
1048 int pagesWide = (alignmentWidth / totalRes) + 1;
1050 final int startRes = (pi % pagesWide) * totalRes;
1051 int endRes = (startRes + totalRes) - 1;
1053 if (endRes > (alignmentWidth - 1))
1055 endRes = alignmentWidth - 1;
1058 final int startSeq = (pi / pagesWide) * totalSeq;
1059 int endSeq = startSeq + totalSeq;
1061 int alignmentHeight = av.getAlignment().getHeight();
1062 if (endSeq > alignmentHeight)
1064 endSeq = alignmentHeight;
1067 int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1070 if (av.isShowAnnotation())
1072 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1075 pagesHigh /= pageHeight;
1077 if (pi >= (pagesWide * pagesHigh))
1079 return Printable.NO_SUCH_PAGE;
1081 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1085 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1087 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1088 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1089 pageWidth - idWidth, scaleHeight);
1090 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1093 * Draw the sequence ids, offset for scale height,
1094 * then reset to top left (0, 0)
1096 idGraphics.translate(0, scaleHeight);
1097 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1098 Color currentColor = null;
1099 Color currentTextColor = null;
1102 for (int i = startSeq; i < endSeq; i++)
1104 seq = av.getAlignment().getSequenceAt(i);
1105 if ((av.getSelectionGroup() != null)
1106 && av.getSelectionGroup().getSequences(null).contains(seq))
1109 * gray out ids of sequences in selection group (if any)
1111 currentColor = Color.gray;
1112 currentTextColor = Color.black;
1116 currentColor = av.getSequenceColour(seq);
1117 currentTextColor = Color.black;
1120 idGraphics.setColor(currentColor);
1121 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1124 idGraphics.setColor(currentTextColor);
1127 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1128 if (av.isRightAlignIds())
1130 fm = idGraphics.getFontMetrics();
1132 - fm.stringWidth(displayId)
1136 idGraphics.drawString(displayId, xPos,
1137 (((i - startSeq) * charHeight) + charHeight)
1138 - (charHeight / 5));
1140 idGraphics.setFont(av.getFont());
1141 idGraphics.translate(0, -scaleHeight);
1144 * draw the sequences, offset for scale height, and id width (if using a
1145 * single graphics context), then reset to (0, scale height)
1147 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1148 getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1149 startSeq, endSeq, 0);
1150 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1152 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1155 * draw annotation labels; drawComponent() translates by
1156 * getScrollOffset(), so compensate for that first;
1157 * then reset to (0, scale height)
1159 int offset = getAlabels().getScrollOffset();
1160 idGraphics.translate(0, -offset);
1161 idGraphics.translate(0, alignmentDrawnHeight);
1162 getAlabels().drawComponent(idGraphics, idWidth);
1163 idGraphics.translate(0, -alignmentDrawnHeight);
1166 * draw the annotations starting at
1167 * (idOffset, alignmentHeight) from (0, scaleHeight)
1169 alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1170 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1171 alignmentGraphics, -1, startRes, endRes + 1);
1174 return Printable.PAGE_EXISTS;
1189 * @return DOCUMENT ME!
1191 * @throws PrinterException
1194 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1195 Graphics pg) throws PrinterException
1197 int annotationHeight = 0;
1198 AnnotationLabels labels = null;
1199 if (av.isShowAnnotation())
1201 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1202 labels = new AnnotationLabels(av);
1205 int hgap = av.getCharHeight();
1206 if (av.getScaleAboveWrapped())
1208 hgap += av.getCharHeight();
1211 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1214 int idWidth = getVisibleIdWidth(false);
1216 int maxwidth = av.getAlignment().getWidth();
1217 if (av.hasHiddenColumns())
1219 maxwidth = av.getAlignment().getHiddenColumns()
1220 .findColumnPosition(maxwidth) - 1;
1223 int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1226 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1228 pg.setColor(Color.white);
1229 pg.fillRect(0, 0, pwidth, pheight);
1230 pg.setFont(av.getFont());
1234 pg.setColor(Color.black);
1236 pg.translate(0, -pi * pheight);
1238 pg.setClip(0, pi * pheight, pwidth, pheight);
1244 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1246 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1247 SequenceI s = av.getAlignment().getSequenceAt(i);
1248 String string = s.getDisplayId(av.getShowJVSuffix());
1250 if (av.isRightAlignIds())
1252 FontMetrics fm = pg.getFontMetrics();
1253 xPos = idWidth - fm.stringWidth(string) - 4;
1255 pg.drawString(string, xPos,
1256 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1257 - (av.getCharHeight() / 5));
1262 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1264 pg.setFont(av.getFont());
1265 labels.drawComponent(pg, idWidth);
1269 - (av.getAlignment().getHeight() * av
1274 } while (ypos < totalHeight);
1276 pg.translate(idWidth, 0);
1278 getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1281 if ((pi * pheight) < totalHeight)
1283 return Printable.PAGE_EXISTS;
1288 return Printable.NO_SUCH_PAGE;
1293 * get current sequence ID panel width, or nominal value if panel were to be
1294 * displayed using default settings
1298 public int getVisibleIdWidth()
1300 return getVisibleIdWidth(true);
1304 * get current sequence ID panel width, or nominal value if panel were to be
1305 * displayed using default settings
1308 * indicate if the Id width for onscreen or offscreen display should
1312 public int getVisibleIdWidth(boolean onscreen)
1314 // see if rendering offscreen - check preferences and calc width accordingly
1315 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1317 return calculateIdWidth(-1).width + 4;
1319 Integer idwidth = null;
1321 || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1323 int w = getIdPanel().getWidth();
1324 return (w > 0 ? w : calculateIdWidth().width + 4);
1326 return idwidth.intValue() + 4;
1329 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1331 int boarderBottomOffset = 5;
1332 long pSessionId = System.currentTimeMillis();
1333 headless = (System.getProperty("java.awt.headless") != null && System
1334 .getProperty("java.awt.headless").equals("true"));
1335 if (alignFrame != null && !headless)
1339 alignFrame.setProgressBar(MessageManager.formatMessage(
1340 "status.saving_file", new Object[] { type.getLabel() }),
1346 AlignmentDimension aDimension = getAlignmentDimension();
1349 jalview.util.ImageMaker im;
1350 final String imageAction, imageTitle;
1351 if (type == jalview.util.ImageMaker.TYPE.PNG)
1353 imageAction = "Create PNG image from alignment";
1356 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1358 imageAction = "Create EPS file from alignment";
1359 imageTitle = alignFrame.getTitle();
1363 imageAction = "Create SVG file from alignment";
1364 imageTitle = alignFrame.getTitle();
1367 im = new jalview.util.ImageMaker(this, type, imageAction,
1368 aDimension.getWidth(), aDimension.getHeight()
1369 + boarderBottomOffset, file, imageTitle,
1370 alignFrame, pSessionId, headless);
1371 Graphics graphics = im.getGraphics();
1372 if (av.getWrapAlignment())
1374 if (graphics != null)
1376 printWrappedAlignment(aDimension.getWidth(),
1377 aDimension.getHeight() + boarderBottomOffset, 0,
1384 if (graphics != null)
1386 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1387 0, graphics, graphics);
1392 } catch (OutOfMemoryError err)
1395 System.out.println("########################\n" + "OUT OF MEMORY "
1396 + file + "\n" + "########################");
1397 new OOMWarning("Creating Image for " + file, err);
1398 // System.out.println("Create IMAGE: " + err);
1399 } catch (Exception ex)
1401 ex.printStackTrace();
1409 public AlignmentDimension getAlignmentDimension()
1411 int maxwidth = av.getAlignment().getWidth();
1412 if (av.hasHiddenColumns())
1414 maxwidth = av.getAlignment().getHiddenColumns()
1415 .findColumnPosition(maxwidth);
1418 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1419 + getScalePanel().getHeight();
1420 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1422 if (av.getWrapAlignment())
1424 height = getWrappedHeight();
1427 // need to obtain default alignment width and then add in any
1428 // additional allowance for id margin
1429 // this duplicates the calculation in getWrappedHeight but adjusts for
1431 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1432 - alignFrame.getInsets().left
1433 - alignFrame.getInsets().right - getVisibleIdWidth()
1434 + getVisibleIdWidth(false);
1438 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1442 else if (av.isShowAnnotation())
1444 height += getAnnotationPanel().adjustPanelHeight() + 3;
1446 return new AlignmentDimension(width, height);
1453 public void makeEPS(File epsFile)
1455 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1461 public void makePNG(File pngFile)
1463 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1466 public void makeSVG(File svgFile)
1468 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1471 public void makePNGImageMap(File imgMapFile, String imageName)
1473 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1474 // ////////////////////////////////////////////
1475 int idWidth = getVisibleIdWidth(false);
1476 FontMetrics fm = getFontMetrics(av.getFont());
1477 int scaleHeight = av.getCharHeight() + fm.getDescent();
1480 // ////////////////////////////////
1481 if (imgMapFile != null)
1485 int s, sSize = av.getAlignment().getHeight(), res, alwidth = av
1486 .getAlignment().getWidth(), g, gSize, f, fSize, sy;
1487 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1488 out.println(jalview.io.HTMLOutput.getImageMapHTML());
1489 out.println("<img src=\"" + imageName
1490 + "\" border=\"0\" usemap=\"#Map\" >"
1491 + "<map name=\"Map\">");
1493 for (s = 0; s < sSize; s++)
1495 sy = s * av.getCharHeight() + scaleHeight;
1497 SequenceI seq = av.getAlignment().getSequenceAt(s);
1498 SequenceFeature[] features = seq.getSequenceFeatures();
1499 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1500 for (res = 0; res < alwidth; res++)
1502 StringBuilder text = new StringBuilder();
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 alIndex = 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(alIndex).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 (features != null)
1545 if (text.length() < 1)
1547 text.append("<area shape=\"rect\" coords=\"")
1548 .append((idWidth + res * av.getCharWidth()))
1549 .append(",").append(sy).append(",")
1550 .append((idWidth + (res + 1) * av.getCharWidth()))
1551 .append(",").append((av.getCharHeight() + sy))
1552 .append("\"").append(" onMouseOver=\"toolTip('")
1553 .append(alIndex).append(" ").append(triplet);
1555 fSize = features.length;
1556 for (f = 0; f < fSize; f++)
1559 if ((features[f].getBegin() <= seq.findPosition(res))
1560 && (features[f].getEnd() >= seq.findPosition(res)))
1562 if (features[f].isContactFeature())
1564 if (features[f].getBegin() == seq.findPosition(res)
1565 || features[f].getEnd() == seq
1568 text.append("<br>").append(features[f].getType())
1569 .append(" ").append(features[f].getBegin())
1570 .append(":").append(features[f].getEnd());
1575 text.append("<br>");
1576 text.append(features[f].getType());
1577 if (features[f].getDescription() != null
1578 && !features[f].getType().equals(
1579 features[f].getDescription()))
1581 text.append(" ").append(features[f].getDescription());
1584 if (features[f].getValue("status") != null)
1586 text.append(" (").append(features[f].getValue("status"))
1594 if (text.length() > 1)
1596 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1597 out.println(text.toString());
1601 out.println("</map></body></html>");
1604 } catch (Exception ex)
1606 ex.printStackTrace();
1608 } // /////////END OF IMAGE MAP
1612 int getWrappedHeight()
1614 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1616 if (System.getProperty("java.awt.headless") != null
1617 && System.getProperty("java.awt.headless").equals("true"))
1619 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1620 - vscroll.getPreferredSize().width
1621 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1624 int chunkWidth = getSeqPanel().seqCanvas
1625 .getWrappedCanvasWidth(seqPanelWidth);
1627 int hgap = av.getCharHeight();
1628 if (av.getScaleAboveWrapped())
1630 hgap += av.getCharHeight();
1633 int annotationHeight = 0;
1634 if (av.isShowAnnotation())
1636 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1639 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1642 int maxwidth = av.getAlignment().getWidth();
1643 if (av.hasHiddenColumns())
1645 maxwidth = av.getAlignment().getHiddenColumns()
1646 .findColumnPosition(maxwidth) - 1;
1649 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1655 * close the panel - deregisters all listeners and nulls any references to
1658 public void closePanel()
1660 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1661 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1662 PaintRefresher.RemoveComponent(this);
1667 * try to ensure references are nulled
1669 if (annotationPanel != null)
1671 annotationPanel.dispose();
1676 av.removePropertyChangeListener(propertyChangeListener);
1677 jalview.structure.StructureSelectionManager ssm = av
1678 .getStructureSelectionManager();
1679 ssm.removeStructureViewerListener(getSeqPanel(), null);
1680 ssm.removeSelectionListener(getSeqPanel());
1681 ssm.removeCommandListener(av);
1682 ssm.removeStructureViewerListener(getSeqPanel(), null);
1683 ssm.removeSelectionListener(getSeqPanel());
1689 if (Cache.log.isDebugEnabled())
1691 Cache.log.warn("Closing alignment panel which is already closed.");
1697 * Close any open dialogs that would be orphaned when this one is closed
1699 protected void closeChildFrames()
1701 if (calculationDialog != null)
1703 calculationDialog.closeFrame();
1708 * hides or shows dynamic annotation rows based on groups and av state flags
1710 public void updateAnnotation()
1712 updateAnnotation(false, false);
1715 public void updateAnnotation(boolean applyGlobalSettings)
1717 updateAnnotation(applyGlobalSettings, false);
1720 public void updateAnnotation(boolean applyGlobalSettings,
1721 boolean preserveNewGroupSettings)
1723 av.updateGroupAnnotationSettings(applyGlobalSettings,
1724 preserveNewGroupSettings);
1725 adjustAnnotationHeight();
1729 public AlignmentI getAlignment()
1731 return av == null ? null : av.getAlignment();
1735 public String getViewName()
1741 * Make/Unmake this alignment panel the current input focus
1745 public void setSelected(boolean b)
1749 if (alignFrame.getSplitViewContainer() != null)
1752 * bring enclosing SplitFrame to front first if there is one
1754 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1756 alignFrame.setSelected(b);
1757 } catch (Exception ex)
1763 alignFrame.setDisplayedView(this);
1768 public StructureSelectionManager getStructureSelectionManager()
1770 return av.getStructureSelectionManager();
1774 public void raiseOOMWarning(String string, OutOfMemoryError error)
1776 new OOMWarning(string, error, this);
1780 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1783 return new FeatureRenderer(this);
1787 public jalview.api.FeatureRenderer getFeatureRenderer()
1789 return seqPanel.seqCanvas.getFeatureRenderer();
1792 public void updateFeatureRenderer(
1793 jalview.renderer.seqfeatures.FeatureRenderer fr)
1795 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1798 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1800 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1802 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1806 public ScalePanel getScalePanel()
1811 public void setScalePanel(ScalePanel scalePanel)
1813 this.scalePanel = scalePanel;
1816 public SeqPanel getSeqPanel()
1821 public void setSeqPanel(SeqPanel seqPanel)
1823 this.seqPanel = seqPanel;
1826 public AnnotationPanel getAnnotationPanel()
1828 return annotationPanel;
1831 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1833 this.annotationPanel = annotationPanel;
1836 public AnnotationLabels getAlabels()
1841 public void setAlabels(AnnotationLabels alabels)
1843 this.alabels = alabels;
1846 public IdPanel getIdPanel()
1851 public void setIdPanel(IdPanel idPanel)
1853 this.idPanel = idPanel;
1857 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1858 * The aim is to keep the two alignments 'lined up' on their centre columns.
1861 * holds mapped region(s) of this alignment that we are scrolling
1862 * 'to'; may be modified for sequence offset by this method
1863 * @param verticalOffset
1864 * the number of visible sequences to show above the mapped region
1866 public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1869 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1870 * mapped), we can make the scroll-to location a sequence above the one
1873 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1874 List<SequenceI> seqs = av.getAlignment().getSequences();
1877 * This is like AlignmentI.findIndex(seq) but here we are matching the
1878 * dataset sequence not the aligned sequence
1880 boolean matched = false;
1881 for (SequenceI seq : seqs)
1883 if (mappedTo == seq.getDatasetSequence())
1891 return; // failsafe, shouldn't happen
1895 * Scroll to position but centring the target residue.
1897 scrollToPosition(sr, verticalOffset, true, true);
1901 * Set a flag to say do not scroll any (cDNA/protein) complement.
1905 protected void setDontScrollComplement(boolean b)
1907 this.dontScrollComplement = b;
1910 protected boolean isDontScrollComplement()
1912 return this.dontScrollComplement;
1918 * @adjustHeight if true, try to recalculate panel height for visible
1921 protected void refresh(boolean adjustHeight)
1923 validateAnnotationDimensions(adjustHeight);
1927 // sort, repaint, update overview
1928 paintAlignment(true);
1932 // lightweight repaint
1938 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1939 * reference should be nulled when the dialog is closed.
1941 * @param calculationChooser
1943 public void setCalculationDialog(CalculationChooser calculationChooser)
1945 calculationDialog = calculationChooser;
1949 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1952 public CalculationChooser getCalculationDialog()
1954 return calculationDialog;