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.SearchResultsI;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceGroup;
31 import jalview.datamodel.SequenceI;
32 import jalview.jbgui.GAlignmentPanel;
33 import jalview.math.AlignmentDimension;
34 import jalview.schemes.ResidueProperties;
35 import jalview.structure.StructureSelectionManager;
36 import jalview.util.MessageManager;
37 import jalview.util.Platform;
38 import jalview.viewmodel.ViewportRanges;
40 import java.awt.BorderLayout;
41 import java.awt.Color;
42 import java.awt.Container;
43 import java.awt.Dimension;
45 import java.awt.FontMetrics;
46 import java.awt.Graphics;
47 import java.awt.Insets;
48 import java.awt.event.AdjustmentEvent;
49 import java.awt.event.AdjustmentListener;
50 import java.awt.print.PageFormat;
51 import java.awt.print.Printable;
52 import java.awt.print.PrinterException;
53 import java.beans.PropertyChangeEvent;
54 import java.beans.PropertyChangeListener;
56 import java.io.FileWriter;
57 import java.io.PrintWriter;
58 import java.util.List;
60 import javax.swing.SwingUtilities;
66 * @version $Revision: 1.161 $
68 public class AlignmentPanel extends GAlignmentPanel implements
69 AdjustmentListener, Printable, AlignmentViewPanel
71 public AlignViewport av;
73 ViewportRanges vpRanges;
75 OverviewPanel overviewPanel;
77 private SeqPanel seqPanel;
79 private IdPanel idPanel;
81 private boolean headless;
83 IdwidthAdjuster idwidthAdjuster;
86 public AlignFrame alignFrame;
88 private ScalePanel scalePanel;
90 private AnnotationPanel annotationPanel;
92 private AnnotationLabels alabels;
94 // this value is set false when selection area being dragged
95 boolean fastPaint = true;
97 private int hextent = 0;
99 private int vextent = 0;
102 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
103 * true, suppresses invoking the same method recursively.
105 private boolean dontScrollComplement;
107 private PropertyChangeListener propertyChangeListener;
109 private CalculationChooser calculationDialog;
112 * Creates a new AlignmentPanel object.
117 public AlignmentPanel(AlignFrame af, final AlignViewport av)
121 vpRanges = av.getRanges();
122 setSeqPanel(new SeqPanel(av, this));
123 setIdPanel(new IdPanel(av, this));
125 setScalePanel(new ScalePanel(av, this));
127 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
128 idwidthAdjuster = new IdwidthAdjuster(this);
129 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
131 setAnnotationPanel(new AnnotationPanel(this));
132 setAlabels(new AnnotationLabels(this));
134 annotationScroller.setViewportView(getAnnotationPanel());
135 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
137 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
138 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
140 setScrollValues(0, 0);
142 hscroll.addAdjustmentListener(this);
143 vscroll.addAdjustmentListener(this);
145 final AlignmentPanel ap = this;
146 propertyChangeListener = new PropertyChangeListener()
149 public void propertyChange(PropertyChangeEvent evt)
151 if (evt.getPropertyName().equals("alignment"))
153 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
158 av.addPropertyChangeListener(propertyChangeListener);
160 adjustAnnotationHeight();
165 public AlignViewportI getAlignViewport()
170 public void alignmentChanged()
172 av.alignmentChanged(this);
174 if (getCalculationDialog() != null)
176 getCalculationDialog().validateCalcTypes();
179 alignFrame.updateEditMenuBar();
181 paintAlignment(true);
188 public void fontChanged()
190 // set idCanvas bufferedImage to null
191 // to prevent drawing old image
192 FontMetrics fm = getFontMetrics(av.getFont());
194 scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
196 idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
197 .getCharHeight() + fm.getDescent()));
199 getIdPanel().getIdCanvas().gg = null;
200 getSeqPanel().seqCanvas.img = null;
201 getAnnotationPanel().adjustPanelHeight();
203 Dimension d = calculateIdWidth();
205 d.setSize(d.width + 4, d.height);
206 getIdPanel().getIdCanvas().setPreferredSize(d);
207 hscrollFillerPanel.setPreferredSize(d);
209 if (overviewPanel != null)
211 overviewPanel.setBoxPosition();
213 if (this.alignFrame.getSplitViewContainer() != null)
215 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
222 * Calculate the width of the alignment labels based on the displayed names
223 * and any bounds on label width set in preferences.
225 * @return Dimension giving the maximum width of the alignment label panel
226 * that should be used.
228 public Dimension calculateIdWidth()
230 // calculate sensible default width when no preference is available
232 if (av.getIdWidth() < 0)
234 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
235 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
236 r = calculateIdWidth(maxwidth);
237 av.setIdWidth(r.width);
242 r.width = av.getIdWidth();
249 * Calculate the width of the alignment labels based on the displayed names
250 * and any bounds on label width set in preferences.
253 * -1 or maximum width allowed for IdWidth
254 * @return Dimension giving the maximum width of the alignment label panel
255 * that should be used.
257 public Dimension calculateIdWidth(int maxwidth)
259 Container c = new Container();
261 FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
262 Font.ITALIC, av.font.getSize()));
264 AlignmentI al = av.getAlignment();
269 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
271 SequenceI s = al.getSequenceAt(i);
273 id = s.getDisplayId(av.getShowJVSuffix());
275 if (fm.stringWidth(id) > idWidth)
277 idWidth = fm.stringWidth(id);
283 // Also check annotation label widths
286 if (al.getAlignmentAnnotation() != null)
288 fm = c.getFontMetrics(getAlabels().getFont());
290 while (i < al.getAlignmentAnnotation().length)
292 String label = al.getAlignmentAnnotation()[i].label;
294 if (fm.stringWidth(label) > idWidth)
296 idWidth = fm.stringWidth(label);
303 return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
308 * Highlight the given results on the alignment.
311 public void highlightSearchResults(SearchResultsI results)
313 scrollToPosition(results);
314 getSeqPanel().seqCanvas.highlightSearchResults(results);
318 * Scroll the view to show the position of the highlighted region in results
319 * (if any) and redraw the overview
323 public boolean scrollToPosition(SearchResultsI results)
325 return scrollToPosition(results, 0, true, false);
329 * Scroll the view to show the position of the highlighted region in results
332 * @param searchResults
333 * @param redrawOverview
336 public boolean scrollToPosition(SearchResultsI searchResults,
337 boolean redrawOverview)
339 return scrollToPosition(searchResults, 0, redrawOverview, false);
343 * Scroll the view to show the position of the highlighted region in results
347 * @param verticalOffset
348 * if greater than zero, allows scrolling to a position below the
349 * first displayed sequence
350 * @param redrawOverview
351 * - when set, the overview will be recalculated (takes longer)
353 * if true, try to centre the search results horizontally in the view
354 * @return false if results were not found
356 public boolean scrollToPosition(SearchResultsI results,
357 int verticalOffset, boolean redrawOverview, boolean centre)
359 int startv, endv, starts, ends;
360 // TODO: properly locate search results in view when large numbers of hidden
361 // columns exist before highlighted region
362 // do we need to scroll the panel?
363 // TODO: tons of nullpointerexceptions raised here.
364 if (results != null && results.getSize() > 0 && av != null
365 && av.getAlignment() != null)
367 int seqIndex = av.getAlignment().findIndex(results);
372 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
374 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
382 // System.err.println(this.av.viewName + " Seq : " + seqIndex
383 // + " Scroll to " + start + "," + end);
386 * To centre results, scroll to positions half the visible width
387 * left/right of the start/end positions
391 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
392 start = Math.max(start - offset, 0);
393 end = end + offset - 1;
399 if (end == seq.getEnd())
403 if (av.hasHiddenColumns())
405 start = av.getColumnSelection().findColumnPosition(start);
406 end = av.getColumnSelection().findColumnPosition(end);
409 if (!av.getColumnSelection().isVisible(r[0]))
411 // don't scroll - position isn't visible
418 * allow for offset of target sequence (actually scroll to one above it)
420 seqIndex = Math.max(0, seqIndex - verticalOffset);
422 // System.out.println("start=" + start + ", end=" + end + ", startv="
423 // + av.getStartRes() + ", endv=" + av.getEndRes() + ", starts="
424 // + av.getStartSeq() + ", ends=" + av.getEndSeq());
425 if (!av.getWrapAlignment())
427 if ((startv = vpRanges.getStartRes()) >= start)
430 * Scroll left to make start of search results visible
432 // setScrollValues(start - 1, seqIndex); // plus one residue
433 setScrollValues(start, seqIndex);
435 else if ((endv = vpRanges.getEndRes()) <= end)
438 * Scroll right to make end of search results visible
440 // setScrollValues(startv + 1 + end - endv, seqIndex); // plus one
441 setScrollValues(startv + end - endv, seqIndex);
443 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
446 * Scroll up to make start of search results visible
448 setScrollValues(vpRanges.getStartRes(), seqIndex);
450 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
453 * Scroll down to make end of search results visible
455 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
459 * Else results are already visible - no need to scroll
464 scrollToWrappedVisible(start);
467 if (redrawOverview && overviewPanel != null)
469 overviewPanel.setBoxPosition();
471 paintAlignment(redrawOverview);
475 void scrollToWrappedVisible(int res)
477 int cwidth = getSeqPanel().seqCanvas
478 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
479 if (res < vpRanges.getStartRes()
480 || res >= (vpRanges.getStartRes() + cwidth))
482 vscroll.setValue((res / cwidth));
483 vpRanges.setStartRes(vscroll.getValue() * cwidth);
491 * @return DOCUMENT ME!
493 public OverviewPanel getOverviewPanel()
495 return overviewPanel;
504 public void setOverviewPanel(OverviewPanel op)
512 * Hide or show annotation panel
515 public void setAnnotationVisible(boolean b)
517 if (!av.getWrapAlignment())
519 annotationSpaceFillerHolder.setVisible(b);
520 annotationScroller.setVisible(b);
526 * automatically adjust annotation panel height for new annotation whilst
527 * ensuring the alignment is still visible.
530 public void adjustAnnotationHeight()
532 // TODO: display vertical annotation scrollbar if necessary
533 // this is called after loading new annotation onto alignment
534 if (alignFrame.getHeight() == 0)
536 System.out.println("NEEDS FIXING");
538 validateAnnotationDimensions(true);
540 paintAlignment(true);
544 * calculate the annotation dimensions and refresh slider values accordingly.
545 * need to do repaints/notifys afterwards.
547 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
549 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
551 if (adjustPanelHeight)
553 int rowHeight = av.getCharHeight();
554 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
557 * Estimate available height in the AlignFrame for alignment +
558 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
559 * hscroll, status bar (as these are not laid out we can't inspect their
560 * actual heights). Insets gives frame borders.
562 int stuff = Platform.isAMac() ? 80 : 100;
563 Insets insets = alignFrame.getInsets();
564 int availableHeight = alignFrame.getHeight() - stuff - insets.top
568 * If not enough vertical space, maximize annotation height while keeping
569 * at least two rows of alignment visible
571 if (annotationHeight + alignmentHeight > availableHeight)
573 annotationHeight = Math.min(annotationHeight, availableHeight - 2
579 // maintain same window layout whilst updating sliders
580 annotationHeight = annotationScroller.getSize().height;
584 annotationScroller.setPreferredSize(new Dimension(annotationScroller
585 .getWidth(), annotationHeight));
587 Dimension e = idPanel.getSize();
588 alabels.setSize(new Dimension(e.width, annotationHeight));
590 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
591 annotationSpaceFillerHolder.getWidth(), annotationHeight));
592 annotationScroller.validate();
593 annotationScroller.addNotify();
597 * update alignment layout for viewport settings
602 public void updateLayout()
605 setAnnotationVisible(av.isShowAnnotation());
606 boolean wrap = av.getWrapAlignment();
607 vpRanges.setStartSeq(0);
608 scalePanelHolder.setVisible(!wrap);
609 hscroll.setVisible(!wrap);
610 idwidthAdjuster.setVisible(!wrap);
614 annotationScroller.setVisible(false);
615 annotationSpaceFillerHolder.setVisible(false);
617 else if (av.isShowAnnotation())
619 annotationScroller.setVisible(true);
620 annotationSpaceFillerHolder.setVisible(true);
623 idSpaceFillerPanel1.setVisible(!wrap);
628 // return value is true if the scroll is valid
629 public boolean scrollUp(boolean up)
633 if (vscroll.getValue() < 1)
639 vscroll.setValue(vscroll.getValue() - 1);
643 if ((vextent + vscroll.getValue()) >= av.getAlignment().getHeight())
649 vscroll.setValue(vscroll.getValue() + 1);
663 * @return DOCUMENT ME!
665 public boolean scrollRight(boolean right)
669 if (hscroll.getValue() < 1)
675 hscroll.setValue(hscroll.getValue() - 1);
679 if ((hextent + hscroll.getValue()) >= av.getAlignment().getWidth())
685 hscroll.setValue(hscroll.getValue() + 1);
694 * Adjust row/column scrollers to show a visible position in the alignment.
697 * visible column to scroll to
699 * visible row to scroll to
702 public void setScrollValues(int x, int y)
704 if (av == null || av.getAlignment() == null)
708 int width = av.getAlignment().getWidth();
709 int height = av.getAlignment().getHeight();
711 if (av.hasHiddenColumns())
713 // reset the width to exclude hidden columns
714 width = av.getColumnSelection().findColumnPosition(width);
717 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
718 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
725 if (vextent > height)
730 if ((hextent + x) > width)
735 if ((vextent + y) > height)
737 y = height - vextent;
750 // update endRes after x has (possibly) been adjusted
751 vpRanges.setEndRes((x + (getSeqPanel().seqCanvas.getWidth() / av
752 .getCharWidth())) - 1);
755 * each scroll adjustment triggers adjustmentValueChanged, which resets the
756 * 'do not scroll complement' flag; ensure it is the same for both
759 boolean flag = isDontScrollComplement();
760 hscroll.setValues(x, hextent, 0, width);
761 setDontScrollComplement(flag);
762 vscroll.setValues(y, vextent, 0, height);
772 public void adjustmentValueChanged(AdjustmentEvent evt)
774 int oldX = vpRanges.getStartRes();
775 int oldY = vpRanges.getStartSeq();
777 if (evt.getSource() == hscroll)
779 int x = hscroll.getValue();
780 vpRanges.setStartRes(x);
781 vpRanges.setEndRes((x + (getSeqPanel().seqCanvas.getWidth() / av
782 .getCharWidth())) - 1);
785 if (evt.getSource() == vscroll)
787 int offy = vscroll.getValue();
789 if (av.getWrapAlignment())
793 int rowSize = getSeqPanel().seqCanvas
794 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
795 vpRanges.setStartRes(offy * rowSize);
796 vpRanges.setEndRes((offy + 1) * rowSize);
800 // This is only called if file loaded is a jar file that
801 // was wrapped when saved and user has wrap alignment true
802 // as preference setting
803 SwingUtilities.invokeLater(new Runnable()
808 setScrollValues(vpRanges.getStartRes(),
809 vpRanges.getStartSeq());
816 vpRanges.setStartSeq(offy);
817 vpRanges.setEndSeq(offy
818 + (getSeqPanel().seqCanvas.getHeight() / av.getCharHeight())
823 if (overviewPanel != null)
825 overviewPanel.setBoxPosition();
828 int scrollX = vpRanges.getStartRes() - oldX;
829 int scrollY = vpRanges.getStartSeq() - oldY;
831 if (av.getWrapAlignment() || !fastPaint)
837 // Make sure we're not trying to draw a panel
838 // larger than the visible window
839 if (scrollX > vpRanges.getEndRes() - vpRanges.getStartRes())
841 scrollX = vpRanges.getEndRes() - vpRanges.getStartRes();
843 else if (scrollX < vpRanges.getStartRes() - vpRanges.getEndRes())
845 scrollX = vpRanges.getStartRes() - vpRanges.getEndRes();
848 if (scrollX != 0 || scrollY != 0)
850 getIdPanel().getIdCanvas().fastPaint(scrollY);
851 getSeqPanel().seqCanvas.fastPaint(scrollX, scrollY);
852 getScalePanel().repaint();
854 if (av.isShowAnnotation() && scrollX != 0)
856 getAnnotationPanel().fastPaint(scrollX);
861 * If there is one, scroll the (Protein/cDNA) complementary alignment to
862 * match, unless we are ourselves doing that.
864 if (isDontScrollComplement())
866 setDontScrollComplement(false);
870 av.scrollComplementaryAlignment();
875 * Repaint the alignment including the annotations and overview panels (if
879 public void paintAlignment(boolean updateOverview)
881 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
882 av.isShowAutocalculatedAbove());
883 sorter.sort(getAlignment().getAlignmentAnnotation(),
884 av.getSortAnnotationsBy());
889 // TODO: determine if this paintAlignment changed structure colours
890 av.getStructureSelectionManager().sequenceColoursChanged(this);
892 if (overviewPanel != null)
894 overviewPanel.updateOverviewImage();
906 public void paintComponent(Graphics g)
910 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
911 idPanelHolder.setPreferredSize(d);
912 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
916 * set scroll bar positions; first suppress this being 'followed' in any
917 * complementary split pane
919 setDontScrollComplement(true);
921 if (av.getWrapAlignment())
923 int maxwidth = av.getAlignment().getWidth();
925 if (av.hasHiddenColumns())
927 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
930 int canvasWidth = getSeqPanel().seqCanvas
931 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
935 / getSeqPanel().seqCanvas
936 .getWrappedCanvasWidth(getSeqPanel().seqCanvas
938 vscroll.setMaximum(max);
939 vscroll.setUnitIncrement(1);
940 vscroll.setVisibleAmount(1);
945 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
959 * @return DOCUMENT ME!
961 * @throws PrinterException
965 public int print(Graphics pg, PageFormat pf, int pi)
966 throws PrinterException
968 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
970 int pwidth = (int) pf.getImageableWidth();
971 int pheight = (int) pf.getImageableHeight();
973 if (av.getWrapAlignment())
975 return printWrappedAlignment(pwidth, pheight, pi, pg);
979 return printUnwrapped(pwidth, pheight, pi, pg, pg);
995 * @return DOCUMENT ME!
997 * @throws PrinterException
1001 * Draws the alignment image, including sequence ids, sequences, and
1002 * annotation labels and annotations if shown, on either one or two Graphics
1009 * the graphics context for sequence ids and annotation labels
1010 * @param alignmentGraphics
1011 * the graphics context for sequences and annotations (may or may not
1012 * be the same context as idGraphics)
1014 * @throws PrinterException
1016 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
1017 Graphics idGraphics, Graphics alignmentGraphics)
1018 throws PrinterException
1020 final int idWidth = getVisibleIdWidth(false);
1023 * Get the horizontal offset to where we draw the sequences.
1024 * This is idWidth if using a single Graphics context, else zero.
1026 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
1028 FontMetrics fm = getFontMetrics(av.getFont());
1029 int charHeight = av.getCharHeight();
1030 int scaleHeight = charHeight + fm.getDescent();
1032 idGraphics.setColor(Color.white);
1033 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1034 idGraphics.setFont(av.getFont());
1037 * How many sequences and residues can we fit on a printable page?
1039 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1041 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1043 int alignmentWidth = av.getAlignment().getWidth();
1044 int pagesWide = (alignmentWidth / totalRes) + 1;
1046 final int startRes = (pi % pagesWide) * totalRes;
1047 int endRes = (startRes + totalRes) - 1;
1049 if (endRes > (alignmentWidth - 1))
1051 endRes = alignmentWidth - 1;
1054 final int startSeq = (pi / pagesWide) * totalSeq;
1055 int endSeq = startSeq + totalSeq;
1057 int alignmentHeight = av.getAlignment().getHeight();
1058 if (endSeq > alignmentHeight)
1060 endSeq = alignmentHeight;
1063 int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1066 if (av.isShowAnnotation())
1068 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1071 pagesHigh /= pageHeight;
1073 if (pi >= (pagesWide * pagesHigh))
1075 return Printable.NO_SUCH_PAGE;
1077 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1081 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1083 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1084 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1085 pageWidth - idWidth, scaleHeight);
1086 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1089 * Draw the sequence ids, offset for scale height,
1090 * then reset to top left (0, 0)
1092 idGraphics.translate(0, scaleHeight);
1093 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1094 Color currentColor = null;
1095 Color currentTextColor = null;
1098 for (int i = startSeq; i < endSeq; i++)
1100 seq = av.getAlignment().getSequenceAt(i);
1101 if ((av.getSelectionGroup() != null)
1102 && av.getSelectionGroup().getSequences(null).contains(seq))
1105 * gray out ids of sequences in selection group (if any)
1107 currentColor = Color.gray;
1108 currentTextColor = Color.black;
1112 currentColor = av.getSequenceColour(seq);
1113 currentTextColor = Color.black;
1116 idGraphics.setColor(currentColor);
1117 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1120 idGraphics.setColor(currentTextColor);
1123 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1124 if (av.isRightAlignIds())
1126 fm = idGraphics.getFontMetrics();
1128 - fm.stringWidth(displayId)
1132 idGraphics.drawString(displayId, xPos,
1133 (((i - startSeq) * charHeight) + charHeight)
1134 - (charHeight / 5));
1136 idGraphics.setFont(av.getFont());
1137 idGraphics.translate(0, -scaleHeight);
1140 * draw the sequences, offset for scale height, and id width (if using a
1141 * single graphics context), then reset to (0, scale height)
1143 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1144 getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1145 startSeq, endSeq, 0);
1146 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1148 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1151 * draw annotation labels; drawComponent() translates by
1152 * getScrollOffset(), so compensate for that first;
1153 * then reset to (0, scale height)
1155 int offset = getAlabels().getScrollOffset();
1156 idGraphics.translate(0, -offset);
1157 idGraphics.translate(0, alignmentDrawnHeight);
1158 getAlabels().drawComponent(idGraphics, idWidth);
1159 idGraphics.translate(0, -alignmentDrawnHeight);
1162 * draw the annotations starting at
1163 * (idOffset, alignmentHeight) from (0, scaleHeight)
1165 alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1166 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1167 alignmentGraphics, -1, startRes, endRes + 1);
1170 return Printable.PAGE_EXISTS;
1185 * @return DOCUMENT ME!
1187 * @throws PrinterException
1190 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1191 Graphics pg) throws PrinterException
1193 int annotationHeight = 0;
1194 AnnotationLabels labels = null;
1195 if (av.isShowAnnotation())
1197 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1198 labels = new AnnotationLabels(av);
1201 int hgap = av.getCharHeight();
1202 if (av.getScaleAboveWrapped())
1204 hgap += av.getCharHeight();
1207 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1210 int idWidth = getVisibleIdWidth(false);
1212 int maxwidth = av.getAlignment().getWidth();
1213 if (av.hasHiddenColumns())
1215 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1218 int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1221 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1223 pg.setColor(Color.white);
1224 pg.fillRect(0, 0, pwidth, pheight);
1225 pg.setFont(av.getFont());
1229 pg.setColor(Color.black);
1231 pg.translate(0, -pi * pheight);
1233 pg.setClip(0, pi * pheight, pwidth, pheight);
1239 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1241 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1242 SequenceI s = av.getAlignment().getSequenceAt(i);
1243 String string = s.getDisplayId(av.getShowJVSuffix());
1245 if (av.isRightAlignIds())
1247 FontMetrics fm = pg.getFontMetrics();
1248 xPos = idWidth - fm.stringWidth(string) - 4;
1250 pg.drawString(string, xPos,
1251 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1252 - (av.getCharHeight() / 5));
1257 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1259 pg.setFont(av.getFont());
1260 labels.drawComponent(pg, idWidth);
1264 - (av.getAlignment().getHeight() * av
1269 } while (ypos < totalHeight);
1271 pg.translate(idWidth, 0);
1273 getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1276 if ((pi * pheight) < totalHeight)
1278 return Printable.PAGE_EXISTS;
1283 return Printable.NO_SUCH_PAGE;
1288 * get current sequence ID panel width, or nominal value if panel were to be
1289 * displayed using default settings
1293 public int getVisibleIdWidth()
1295 return getVisibleIdWidth(true);
1299 * get current sequence ID panel width, or nominal value if panel were to be
1300 * displayed using default settings
1303 * indicate if the Id width for onscreen or offscreen display should
1307 public int getVisibleIdWidth(boolean onscreen)
1309 // see if rendering offscreen - check preferences and calc width accordingly
1310 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1312 return calculateIdWidth(-1).width + 4;
1314 Integer idwidth = null;
1316 || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1318 int w = getIdPanel().getWidth();
1319 return (w > 0 ? w : calculateIdWidth().width + 4);
1321 return idwidth.intValue() + 4;
1324 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1326 int boarderBottomOffset = 5;
1327 long pSessionId = System.currentTimeMillis();
1328 headless = (System.getProperty("java.awt.headless") != null && System
1329 .getProperty("java.awt.headless").equals("true"));
1330 if (alignFrame != null && !headless)
1334 alignFrame.setProgressBar(MessageManager.formatMessage(
1335 "status.saving_file", new Object[] { type.getLabel() }),
1341 AlignmentDimension aDimension = getAlignmentDimension();
1344 jalview.util.ImageMaker im;
1345 final String imageAction, imageTitle;
1346 if (type == jalview.util.ImageMaker.TYPE.PNG)
1348 imageAction = "Create PNG image from alignment";
1351 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1353 imageAction = "Create EPS file from alignment";
1354 imageTitle = alignFrame.getTitle();
1358 imageAction = "Create SVG file from alignment";
1359 imageTitle = alignFrame.getTitle();
1362 im = new jalview.util.ImageMaker(this, type, imageAction,
1363 aDimension.getWidth(), aDimension.getHeight()
1364 + boarderBottomOffset, file, imageTitle,
1365 alignFrame, pSessionId, headless);
1366 Graphics graphics = im.getGraphics();
1367 if (av.getWrapAlignment())
1369 if (graphics != null)
1371 printWrappedAlignment(aDimension.getWidth(),
1372 aDimension.getHeight() + boarderBottomOffset, 0,
1379 if (graphics != null)
1381 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1382 0, graphics, graphics);
1387 } catch (OutOfMemoryError err)
1390 System.out.println("########################\n" + "OUT OF MEMORY "
1391 + file + "\n" + "########################");
1392 new OOMWarning("Creating Image for " + file, err);
1393 // System.out.println("Create IMAGE: " + err);
1394 } catch (Exception ex)
1396 ex.printStackTrace();
1404 public AlignmentDimension getAlignmentDimension()
1406 int maxwidth = av.getAlignment().getWidth();
1407 if (av.hasHiddenColumns())
1409 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth);
1412 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1413 + getScalePanel().getHeight();
1414 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1416 if (av.getWrapAlignment())
1418 height = getWrappedHeight();
1421 // need to obtain default alignment width and then add in any
1422 // additional allowance for id margin
1423 // this duplicates the calculation in getWrappedHeight but adjusts for
1425 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1426 - alignFrame.getInsets().left
1427 - alignFrame.getInsets().right - getVisibleIdWidth()
1428 + getVisibleIdWidth(false);
1432 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1436 else if (av.isShowAnnotation())
1438 height += getAnnotationPanel().adjustPanelHeight() + 3;
1440 return new AlignmentDimension(width, height);
1447 public void makeEPS(File epsFile)
1449 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1455 public void makePNG(File pngFile)
1457 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1460 public void makeSVG(File svgFile)
1462 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1465 public void makePNGImageMap(File imgMapFile, String imageName)
1467 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1468 // ////////////////////////////////////////////
1469 int idWidth = getVisibleIdWidth(false);
1470 FontMetrics fm = getFontMetrics(av.getFont());
1471 int scaleHeight = av.getCharHeight() + fm.getDescent();
1474 // ////////////////////////////////
1475 if (imgMapFile != null)
1479 int s, sSize = av.getAlignment().getHeight(), res, alwidth = av
1480 .getAlignment().getWidth(), g, gSize, f, fSize, sy;
1481 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1482 out.println(jalview.io.HTMLOutput.getImageMapHTML());
1483 out.println("<img src=\"" + imageName
1484 + "\" border=\"0\" usemap=\"#Map\" >"
1485 + "<map name=\"Map\">");
1487 for (s = 0; s < sSize; s++)
1489 sy = s * av.getCharHeight() + scaleHeight;
1491 SequenceI seq = av.getAlignment().getSequenceAt(s);
1492 SequenceFeature[] features = seq.getSequenceFeatures();
1493 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1494 for (res = 0; res < alwidth; res++)
1496 StringBuilder text = new StringBuilder();
1497 String triplet = null;
1498 if (av.getAlignment().isNucleotide())
1500 triplet = ResidueProperties.nucleotideName.get(seq
1501 .getCharAt(res) + "");
1505 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(res)
1509 if (triplet == null)
1514 int alIndex = seq.findPosition(res);
1515 gSize = groups.length;
1516 for (g = 0; g < gSize; g++)
1518 if (text.length() < 1)
1520 text.append("<area shape=\"rect\" coords=\"")
1521 .append((idWidth + res * av.getCharWidth()))
1522 .append(",").append(sy).append(",")
1523 .append((idWidth + (res + 1) * av.getCharWidth()))
1524 .append(",").append((av.getCharHeight() + sy))
1525 .append("\"").append(" onMouseOver=\"toolTip('")
1526 .append(alIndex).append(" ").append(triplet);
1529 if (groups[g].getStartRes() < res
1530 && groups[g].getEndRes() > res)
1532 text.append("<br><em>").append(groups[g].getName())
1537 if (features != null)
1539 if (text.length() < 1)
1541 text.append("<area shape=\"rect\" coords=\"")
1542 .append((idWidth + res * av.getCharWidth()))
1543 .append(",").append(sy).append(",")
1544 .append((idWidth + (res + 1) * av.getCharWidth()))
1545 .append(",").append((av.getCharHeight() + sy))
1546 .append("\"").append(" onMouseOver=\"toolTip('")
1547 .append(alIndex).append(" ").append(triplet);
1549 fSize = features.length;
1550 for (f = 0; f < fSize; f++)
1553 if ((features[f].getBegin() <= seq.findPosition(res))
1554 && (features[f].getEnd() >= seq.findPosition(res)))
1556 if (features[f].isContactFeature())
1558 if (features[f].getBegin() == seq.findPosition(res)
1559 || features[f].getEnd() == seq
1562 text.append("<br>").append(features[f].getType())
1563 .append(" ").append(features[f].getBegin())
1564 .append(":").append(features[f].getEnd());
1569 text.append("<br>");
1570 text.append(features[f].getType());
1571 if (features[f].getDescription() != null
1572 && !features[f].getType().equals(
1573 features[f].getDescription()))
1575 text.append(" ").append(features[f].getDescription());
1578 if (features[f].getValue("status") != null)
1580 text.append(" (").append(features[f].getValue("status"))
1588 if (text.length() > 1)
1590 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1591 out.println(text.toString());
1595 out.println("</map></body></html>");
1598 } catch (Exception ex)
1600 ex.printStackTrace();
1602 } // /////////END OF IMAGE MAP
1606 int getWrappedHeight()
1608 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1610 if (System.getProperty("java.awt.headless") != null
1611 && System.getProperty("java.awt.headless").equals("true"))
1613 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1614 - vscroll.getPreferredSize().width
1615 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1618 int chunkWidth = getSeqPanel().seqCanvas
1619 .getWrappedCanvasWidth(seqPanelWidth);
1621 int hgap = av.getCharHeight();
1622 if (av.getScaleAboveWrapped())
1624 hgap += av.getCharHeight();
1627 int annotationHeight = 0;
1628 if (av.isShowAnnotation())
1630 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1633 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1636 int maxwidth = av.getAlignment().getWidth();
1637 if (av.hasHiddenColumns())
1639 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1642 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1648 * close the panel - deregisters all listeners and nulls any references to
1651 public void closePanel()
1653 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1654 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1655 PaintRefresher.RemoveComponent(this);
1660 * try to ensure references are nulled
1662 if (annotationPanel != null)
1664 annotationPanel.dispose();
1669 av.removePropertyChangeListener(propertyChangeListener);
1670 jalview.structure.StructureSelectionManager ssm = av
1671 .getStructureSelectionManager();
1672 ssm.removeStructureViewerListener(getSeqPanel(), null);
1673 ssm.removeSelectionListener(getSeqPanel());
1674 ssm.removeCommandListener(av);
1675 ssm.removeStructureViewerListener(getSeqPanel(), null);
1676 ssm.removeSelectionListener(getSeqPanel());
1682 if (Cache.log.isDebugEnabled())
1684 Cache.log.warn("Closing alignment panel which is already closed.");
1690 * Close any open dialogs that would be orphaned when this one is closed
1692 protected void closeChildFrames()
1694 if (calculationDialog != null)
1696 calculationDialog.closeFrame();
1701 * hides or shows dynamic annotation rows based on groups and av state flags
1703 public void updateAnnotation()
1705 updateAnnotation(false, false);
1708 public void updateAnnotation(boolean applyGlobalSettings)
1710 updateAnnotation(applyGlobalSettings, false);
1713 public void updateAnnotation(boolean applyGlobalSettings,
1714 boolean preserveNewGroupSettings)
1716 av.updateGroupAnnotationSettings(applyGlobalSettings,
1717 preserveNewGroupSettings);
1718 adjustAnnotationHeight();
1722 public AlignmentI getAlignment()
1724 return av == null ? null : av.getAlignment();
1728 public String getViewName()
1734 * Make/Unmake this alignment panel the current input focus
1738 public void setSelected(boolean b)
1742 if (alignFrame.getSplitViewContainer() != null)
1745 * bring enclosing SplitFrame to front first if there is one
1747 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1749 alignFrame.setSelected(b);
1750 } catch (Exception ex)
1756 alignFrame.setDisplayedView(this);
1761 public StructureSelectionManager getStructureSelectionManager()
1763 return av.getStructureSelectionManager();
1767 public void raiseOOMWarning(String string, OutOfMemoryError error)
1769 new OOMWarning(string, error, this);
1773 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1776 return new FeatureRenderer(this);
1780 public jalview.api.FeatureRenderer getFeatureRenderer()
1782 return seqPanel.seqCanvas.getFeatureRenderer();
1785 public void updateFeatureRenderer(
1786 jalview.renderer.seqfeatures.FeatureRenderer fr)
1788 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1791 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1793 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1795 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1799 public ScalePanel getScalePanel()
1804 public void setScalePanel(ScalePanel scalePanel)
1806 this.scalePanel = scalePanel;
1809 public SeqPanel getSeqPanel()
1814 public void setSeqPanel(SeqPanel seqPanel)
1816 this.seqPanel = seqPanel;
1819 public AnnotationPanel getAnnotationPanel()
1821 return annotationPanel;
1824 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1826 this.annotationPanel = annotationPanel;
1829 public AnnotationLabels getAlabels()
1834 public void setAlabels(AnnotationLabels alabels)
1836 this.alabels = alabels;
1839 public IdPanel getIdPanel()
1844 public void setIdPanel(IdPanel idPanel)
1846 this.idPanel = idPanel;
1850 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1851 * The aim is to keep the two alignments 'lined up' on their centre columns.
1854 * holds mapped region(s) of this alignment that we are scrolling
1855 * 'to'; may be modified for sequence offset by this method
1856 * @param verticalOffset
1857 * the number of visible sequences to show above the mapped region
1859 public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1862 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1863 * mapped), we can make the scroll-to location a sequence above the one
1866 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1867 List<SequenceI> seqs = av.getAlignment().getSequences();
1870 * This is like AlignmentI.findIndex(seq) but here we are matching the
1871 * dataset sequence not the aligned sequence
1873 boolean matched = false;
1874 for (SequenceI seq : seqs)
1876 if (mappedTo == seq.getDatasetSequence())
1884 return; // failsafe, shouldn't happen
1888 * Scroll to position but centring the target residue.
1890 scrollToPosition(sr, verticalOffset, true, true);
1894 * Set a flag to say do not scroll any (cDNA/protein) complement.
1898 protected void setDontScrollComplement(boolean b)
1900 this.dontScrollComplement = b;
1903 protected boolean isDontScrollComplement()
1905 return this.dontScrollComplement;
1911 * @adjustHeight if true, try to recalculate panel height for visible
1914 protected void refresh(boolean adjustHeight)
1916 validateAnnotationDimensions(adjustHeight);
1920 // sort, repaint, update overview
1921 paintAlignment(true);
1925 // lightweight repaint
1931 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1932 * reference should be nulled when the dialog is closed.
1934 * @param calculationChooser
1936 public void setCalculationDialog(CalculationChooser calculationChooser)
1938 calculationDialog = calculationChooser;
1942 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1945 public CalculationChooser getCalculationDialog()
1947 return calculationDialog;