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 alignFrame.updateEditMenuBar();
176 paintAlignment(true);
183 public void fontChanged()
185 // set idCanvas bufferedImage to null
186 // to prevent drawing old image
187 FontMetrics fm = getFontMetrics(av.getFont());
189 scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
191 idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
192 .getCharHeight() + fm.getDescent()));
194 getIdPanel().getIdCanvas().gg = null;
195 getSeqPanel().seqCanvas.img = null;
196 getAnnotationPanel().adjustPanelHeight();
198 Dimension d = calculateIdWidth();
200 d.setSize(d.width + 4, d.height);
201 getIdPanel().getIdCanvas().setPreferredSize(d);
202 hscrollFillerPanel.setPreferredSize(d);
204 if (overviewPanel != null)
206 overviewPanel.setBoxPosition();
208 if (this.alignFrame.getSplitViewContainer() != null)
210 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
217 * Calculate the width of the alignment labels based on the displayed names
218 * and any bounds on label width set in preferences.
220 * @return Dimension giving the maximum width of the alignment label panel
221 * that should be used.
223 public Dimension calculateIdWidth()
225 // calculate sensible default width when no preference is available
227 if (av.getIdWidth() < 0)
229 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
230 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
231 r = calculateIdWidth(maxwidth);
232 av.setIdWidth(r.width);
237 r.width = av.getIdWidth();
244 * Calculate the width of the alignment labels based on the displayed names
245 * and any bounds on label width set in preferences.
248 * -1 or maximum width allowed for IdWidth
249 * @return Dimension giving the maximum width of the alignment label panel
250 * that should be used.
252 public Dimension calculateIdWidth(int maxwidth)
254 Container c = new Container();
256 FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
257 Font.ITALIC, av.font.getSize()));
259 AlignmentI al = av.getAlignment();
264 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
266 SequenceI s = al.getSequenceAt(i);
268 id = s.getDisplayId(av.getShowJVSuffix());
270 if (fm.stringWidth(id) > idWidth)
272 idWidth = fm.stringWidth(id);
278 // Also check annotation label widths
281 if (al.getAlignmentAnnotation() != null)
283 fm = c.getFontMetrics(getAlabels().getFont());
285 while (i < al.getAlignmentAnnotation().length)
287 String label = al.getAlignmentAnnotation()[i].label;
289 if (fm.stringWidth(label) > idWidth)
291 idWidth = fm.stringWidth(label);
298 return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
303 * Highlight the given results on the alignment.
306 public void highlightSearchResults(SearchResultsI results)
308 scrollToPosition(results);
309 getSeqPanel().seqCanvas.highlightSearchResults(results);
313 * Scroll the view to show the position of the highlighted region in results
314 * (if any) and redraw the overview
318 public boolean scrollToPosition(SearchResultsI results)
320 return scrollToPosition(results, 0, true, false);
324 * Scroll the view to show the position of the highlighted region in results
327 * @param searchResults
328 * @param redrawOverview
331 public boolean scrollToPosition(SearchResultsI searchResults,
332 boolean redrawOverview)
334 return scrollToPosition(searchResults, 0, redrawOverview, false);
338 * Scroll the view to show the position of the highlighted region in results
342 * @param verticalOffset
343 * if greater than zero, allows scrolling to a position below the
344 * first displayed sequence
345 * @param redrawOverview
346 * - when set, the overview will be recalculated (takes longer)
348 * if true, try to centre the search results horizontally in the view
349 * @return false if results were not found
351 public boolean scrollToPosition(SearchResultsI results,
352 int verticalOffset, boolean redrawOverview, boolean centre)
354 int startv, endv, starts, ends;
355 // TODO: properly locate search results in view when large numbers of hidden
356 // columns exist before highlighted region
357 // do we need to scroll the panel?
358 // TODO: tons of nullpointerexceptions raised here.
359 if (results != null && results.getSize() > 0 && av != null
360 && av.getAlignment() != null)
362 int seqIndex = av.getAlignment().findIndex(results);
367 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
369 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
377 // System.err.println(this.av.viewName + " Seq : " + seqIndex
378 // + " Scroll to " + start + "," + end);
381 * To centre results, scroll to positions half the visible width
382 * left/right of the start/end positions
386 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
387 start = Math.max(start - offset, 0);
388 end = end + offset - 1;
394 if (end == seq.getEnd())
398 if (av.hasHiddenColumns())
400 start = av.getColumnSelection().findColumnPosition(start);
401 end = av.getColumnSelection().findColumnPosition(end);
404 if (!av.getColumnSelection().isVisible(r[0]))
406 // don't scroll - position isn't visible
413 * allow for offset of target sequence (actually scroll to one above it)
415 seqIndex = Math.max(0, seqIndex - verticalOffset);
417 // System.out.println("start=" + start + ", end=" + end + ", startv="
418 // + av.getStartRes() + ", endv=" + av.getEndRes() + ", starts="
419 // + av.getStartSeq() + ", ends=" + av.getEndSeq());
420 if (!av.getWrapAlignment())
422 if ((startv = vpRanges.getStartRes()) >= start)
425 * Scroll left to make start of search results visible
427 // setScrollValues(start - 1, seqIndex); // plus one residue
428 setScrollValues(start, seqIndex);
430 else if ((endv = vpRanges.getEndRes()) <= end)
433 * Scroll right to make end of search results visible
435 // setScrollValues(startv + 1 + end - endv, seqIndex); // plus one
436 setScrollValues(startv + end - endv, seqIndex);
438 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
441 * Scroll up to make start of search results visible
443 setScrollValues(vpRanges.getStartRes(), seqIndex);
445 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
448 * Scroll down to make end of search results visible
450 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
454 * Else results are already visible - no need to scroll
459 scrollToWrappedVisible(start);
462 if (redrawOverview && overviewPanel != null)
464 overviewPanel.setBoxPosition();
466 paintAlignment(redrawOverview);
470 void scrollToWrappedVisible(int res)
472 int cwidth = getSeqPanel().seqCanvas
473 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
474 if (res < vpRanges.getStartRes()
475 || res >= (vpRanges.getStartRes() + cwidth))
477 vscroll.setValue((res / cwidth));
478 vpRanges.setStartRes(vscroll.getValue() * cwidth);
486 * @return DOCUMENT ME!
488 public OverviewPanel getOverviewPanel()
490 return overviewPanel;
499 public void setOverviewPanel(OverviewPanel op)
507 * Hide or show annotation panel
510 public void setAnnotationVisible(boolean b)
512 if (!av.getWrapAlignment())
514 annotationSpaceFillerHolder.setVisible(b);
515 annotationScroller.setVisible(b);
521 * automatically adjust annotation panel height for new annotation whilst
522 * ensuring the alignment is still visible.
525 public void adjustAnnotationHeight()
527 // TODO: display vertical annotation scrollbar if necessary
528 // this is called after loading new annotation onto alignment
529 if (alignFrame.getHeight() == 0)
531 System.out.println("NEEDS FIXING");
533 validateAnnotationDimensions(true);
535 paintAlignment(true);
539 * calculate the annotation dimensions and refresh slider values accordingly.
540 * need to do repaints/notifys afterwards.
542 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
544 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
546 if (adjustPanelHeight)
548 int rowHeight = av.getCharHeight();
549 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
552 * Estimate available height in the AlignFrame for alignment +
553 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
554 * hscroll, status bar (as these are not laid out we can't inspect their
555 * actual heights). Insets gives frame borders.
557 int stuff = Platform.isAMac() ? 80 : 100;
558 Insets insets = alignFrame.getInsets();
559 int availableHeight = alignFrame.getHeight() - stuff - insets.top
563 * If not enough vertical space, maximize annotation height while keeping
564 * at least two rows of alignment visible
566 if (annotationHeight + alignmentHeight > availableHeight)
568 annotationHeight = Math.min(annotationHeight, availableHeight - 2
574 // maintain same window layout whilst updating sliders
575 annotationHeight = annotationScroller.getSize().height;
579 annotationScroller.setPreferredSize(new Dimension(annotationScroller
580 .getWidth(), annotationHeight));
582 Dimension e = idPanel.getSize();
583 alabels.setSize(new Dimension(e.width, annotationHeight));
585 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
586 annotationSpaceFillerHolder.getWidth(), annotationHeight));
587 annotationScroller.validate();
588 annotationScroller.addNotify();
592 * update alignment layout for viewport settings
597 public void updateLayout()
600 setAnnotationVisible(av.isShowAnnotation());
601 boolean wrap = av.getWrapAlignment();
602 vpRanges.setStartSeq(0);
603 scalePanelHolder.setVisible(!wrap);
604 hscroll.setVisible(!wrap);
605 idwidthAdjuster.setVisible(!wrap);
609 annotationScroller.setVisible(false);
610 annotationSpaceFillerHolder.setVisible(false);
612 else if (av.isShowAnnotation())
614 annotationScroller.setVisible(true);
615 annotationSpaceFillerHolder.setVisible(true);
618 idSpaceFillerPanel1.setVisible(!wrap);
623 // return value is true if the scroll is valid
624 public boolean scrollUp(boolean up)
628 if (vscroll.getValue() < 1)
634 vscroll.setValue(vscroll.getValue() - 1);
638 if ((vextent + vscroll.getValue()) >= av.getAlignment().getHeight())
644 vscroll.setValue(vscroll.getValue() + 1);
658 * @return DOCUMENT ME!
660 public boolean scrollRight(boolean right)
664 if (hscroll.getValue() < 1)
670 hscroll.setValue(hscroll.getValue() - 1);
674 if ((hextent + hscroll.getValue()) >= av.getAlignment().getWidth())
680 hscroll.setValue(hscroll.getValue() + 1);
689 * Adjust row/column scrollers to show a visible position in the alignment.
692 * visible column to scroll to
694 * visible row to scroll to
697 public void setScrollValues(int x, int y)
699 if (av == null || av.getAlignment() == null)
703 int width = av.getAlignment().getWidth();
704 int height = av.getAlignment().getHeight();
706 if (av.hasHiddenColumns())
708 // reset the width to exclude hidden columns
709 width = av.getColumnSelection().findColumnPosition(width);
712 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
713 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
720 if (vextent > height)
725 if ((hextent + x) > width)
730 if ((vextent + y) > height)
732 y = height - vextent;
745 // update endRes after x has (possibly) been adjusted
746 vpRanges.setEndRes((x + (getSeqPanel().seqCanvas.getWidth() / av
747 .getCharWidth())) - 1);
750 * each scroll adjustment triggers adjustmentValueChanged, which resets the
751 * 'do not scroll complement' flag; ensure it is the same for both
754 boolean flag = isDontScrollComplement();
755 hscroll.setValues(x, hextent, 0, width);
756 setDontScrollComplement(flag);
757 vscroll.setValues(y, vextent, 0, height);
767 public void adjustmentValueChanged(AdjustmentEvent evt)
769 int oldX = vpRanges.getStartRes();
770 int oldY = vpRanges.getStartSeq();
772 if (evt.getSource() == hscroll)
774 int x = hscroll.getValue();
775 vpRanges.setStartRes(x);
776 vpRanges.setEndRes((x + (getSeqPanel().seqCanvas.getWidth() / av
777 .getCharWidth())) - 1);
780 if (evt.getSource() == vscroll)
782 int offy = vscroll.getValue();
784 if (av.getWrapAlignment())
788 int rowSize = getSeqPanel().seqCanvas
789 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
790 vpRanges.setStartRes(offy * rowSize);
791 vpRanges.setEndRes((offy + 1) * rowSize);
795 // This is only called if file loaded is a jar file that
796 // was wrapped when saved and user has wrap alignment true
797 // as preference setting
798 SwingUtilities.invokeLater(new Runnable()
803 setScrollValues(vpRanges.getStartRes(),
804 vpRanges.getStartSeq());
811 vpRanges.setStartSeq(offy);
812 vpRanges.setEndSeq(offy
813 + (getSeqPanel().seqCanvas.getHeight() / av.getCharHeight())
818 if (overviewPanel != null)
820 overviewPanel.setBoxPosition();
823 int scrollX = vpRanges.getStartRes() - oldX;
824 int scrollY = vpRanges.getStartSeq() - oldY;
826 if (av.getWrapAlignment() || !fastPaint)
832 // Make sure we're not trying to draw a panel
833 // larger than the visible window
834 if (scrollX > vpRanges.getEndRes() - vpRanges.getStartRes())
836 scrollX = vpRanges.getEndRes() - vpRanges.getStartRes();
838 else if (scrollX < vpRanges.getStartRes() - vpRanges.getEndRes())
840 scrollX = vpRanges.getStartRes() - vpRanges.getEndRes();
843 if (scrollX != 0 || scrollY != 0)
845 getIdPanel().getIdCanvas().fastPaint(scrollY);
846 getSeqPanel().seqCanvas.fastPaint(scrollX, scrollY);
847 getScalePanel().repaint();
849 if (av.isShowAnnotation() && scrollX != 0)
851 getAnnotationPanel().fastPaint(scrollX);
856 * If there is one, scroll the (Protein/cDNA) complementary alignment to
857 * match, unless we are ourselves doing that.
859 if (isDontScrollComplement())
861 setDontScrollComplement(false);
865 av.scrollComplementaryAlignment();
870 * Repaint the alignment including the annotations and overview panels (if
874 public void paintAlignment(boolean updateOverview)
876 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
877 av.isShowAutocalculatedAbove());
878 sorter.sort(getAlignment().getAlignmentAnnotation(),
879 av.getSortAnnotationsBy());
884 // TODO: determine if this paintAlignment changed structure colours
885 av.getStructureSelectionManager().sequenceColoursChanged(this);
887 if (overviewPanel != null)
889 overviewPanel.updateOverviewImage();
901 public void paintComponent(Graphics g)
905 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
906 idPanelHolder.setPreferredSize(d);
907 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
911 * set scroll bar positions; first suppress this being 'followed' in any
912 * complementary split pane
914 setDontScrollComplement(true);
916 if (av.getWrapAlignment())
918 int maxwidth = av.getAlignment().getWidth();
920 if (av.hasHiddenColumns())
922 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
925 int canvasWidth = getSeqPanel().seqCanvas
926 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
930 / getSeqPanel().seqCanvas
931 .getWrappedCanvasWidth(getSeqPanel().seqCanvas
933 vscroll.setMaximum(max);
934 vscroll.setUnitIncrement(1);
935 vscroll.setVisibleAmount(1);
940 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
954 * @return DOCUMENT ME!
956 * @throws PrinterException
960 public int print(Graphics pg, PageFormat pf, int pi)
961 throws PrinterException
963 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
965 int pwidth = (int) pf.getImageableWidth();
966 int pheight = (int) pf.getImageableHeight();
968 if (av.getWrapAlignment())
970 return printWrappedAlignment(pwidth, pheight, pi, pg);
974 return printUnwrapped(pwidth, pheight, pi, pg, pg);
990 * @return DOCUMENT ME!
992 * @throws PrinterException
996 * Draws the alignment image, including sequence ids, sequences, and
997 * annotation labels and annotations if shown, on either one or two Graphics
1004 * the graphics context for sequence ids and annotation labels
1005 * @param alignmentGraphics
1006 * the graphics context for sequences and annotations (may or may not
1007 * be the same context as idGraphics)
1009 * @throws PrinterException
1011 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
1012 Graphics idGraphics, Graphics alignmentGraphics)
1013 throws PrinterException
1015 final int idWidth = getVisibleIdWidth(false);
1018 * Get the horizontal offset to where we draw the sequences.
1019 * This is idWidth if using a single Graphics context, else zero.
1021 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
1023 FontMetrics fm = getFontMetrics(av.getFont());
1024 int charHeight = av.getCharHeight();
1025 int scaleHeight = charHeight + fm.getDescent();
1027 idGraphics.setColor(Color.white);
1028 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1029 idGraphics.setFont(av.getFont());
1032 * How many sequences and residues can we fit on a printable page?
1034 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1036 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1038 int alignmentWidth = av.getAlignment().getWidth();
1039 int pagesWide = (alignmentWidth / totalRes) + 1;
1041 final int startRes = (pi % pagesWide) * totalRes;
1042 int endRes = (startRes + totalRes) - 1;
1044 if (endRes > (alignmentWidth - 1))
1046 endRes = alignmentWidth - 1;
1049 final int startSeq = (pi / pagesWide) * totalSeq;
1050 int endSeq = startSeq + totalSeq;
1052 int alignmentHeight = av.getAlignment().getHeight();
1053 if (endSeq > alignmentHeight)
1055 endSeq = alignmentHeight;
1058 int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1061 if (av.isShowAnnotation())
1063 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1066 pagesHigh /= pageHeight;
1068 if (pi >= (pagesWide * pagesHigh))
1070 return Printable.NO_SUCH_PAGE;
1072 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1076 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1078 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1079 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1080 pageWidth - idWidth, scaleHeight);
1081 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1084 * Draw the sequence ids, offset for scale height,
1085 * then reset to top left (0, 0)
1087 idGraphics.translate(0, scaleHeight);
1088 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1089 Color currentColor = null;
1090 Color currentTextColor = null;
1093 for (int i = startSeq; i < endSeq; i++)
1095 seq = av.getAlignment().getSequenceAt(i);
1096 if ((av.getSelectionGroup() != null)
1097 && av.getSelectionGroup().getSequences(null).contains(seq))
1100 * gray out ids of sequences in selection group (if any)
1102 currentColor = Color.gray;
1103 currentTextColor = Color.black;
1107 currentColor = av.getSequenceColour(seq);
1108 currentTextColor = Color.black;
1111 idGraphics.setColor(currentColor);
1112 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1115 idGraphics.setColor(currentTextColor);
1118 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1119 if (av.isRightAlignIds())
1121 fm = idGraphics.getFontMetrics();
1123 - fm.stringWidth(displayId)
1127 idGraphics.drawString(displayId, xPos,
1128 (((i - startSeq) * charHeight) + charHeight)
1129 - (charHeight / 5));
1131 idGraphics.setFont(av.getFont());
1132 idGraphics.translate(0, -scaleHeight);
1135 * draw the sequences, offset for scale height, and id width (if using a
1136 * single graphics context), then reset to (0, scale height)
1138 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1139 getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1140 startSeq, endSeq, 0);
1141 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1143 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1146 * draw annotation labels; drawComponent() translates by
1147 * getScrollOffset(), so compensate for that first;
1148 * then reset to (0, scale height)
1150 int offset = getAlabels().getScrollOffset();
1151 idGraphics.translate(0, -offset);
1152 idGraphics.translate(0, alignmentDrawnHeight);
1153 getAlabels().drawComponent(idGraphics, idWidth);
1154 idGraphics.translate(0, -alignmentDrawnHeight);
1157 * draw the annotations starting at
1158 * (idOffset, alignmentHeight) from (0, scaleHeight)
1160 alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1161 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1162 alignmentGraphics, -1, startRes, endRes + 1);
1165 return Printable.PAGE_EXISTS;
1180 * @return DOCUMENT ME!
1182 * @throws PrinterException
1185 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1186 Graphics pg) throws PrinterException
1188 int annotationHeight = 0;
1189 AnnotationLabels labels = null;
1190 if (av.isShowAnnotation())
1192 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1193 labels = new AnnotationLabels(av);
1196 int hgap = av.getCharHeight();
1197 if (av.getScaleAboveWrapped())
1199 hgap += av.getCharHeight();
1202 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1205 int idWidth = getVisibleIdWidth(false);
1207 int maxwidth = av.getAlignment().getWidth();
1208 if (av.hasHiddenColumns())
1210 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1213 int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1216 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1218 pg.setColor(Color.white);
1219 pg.fillRect(0, 0, pwidth, pheight);
1220 pg.setFont(av.getFont());
1224 pg.setColor(Color.black);
1226 pg.translate(0, -pi * pheight);
1228 pg.setClip(0, pi * pheight, pwidth, pheight);
1234 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1236 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1237 SequenceI s = av.getAlignment().getSequenceAt(i);
1238 String string = s.getDisplayId(av.getShowJVSuffix());
1240 if (av.isRightAlignIds())
1242 FontMetrics fm = pg.getFontMetrics();
1243 xPos = idWidth - fm.stringWidth(string) - 4;
1245 pg.drawString(string, xPos,
1246 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1247 - (av.getCharHeight() / 5));
1252 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1254 pg.setFont(av.getFont());
1255 labels.drawComponent(pg, idWidth);
1259 - (av.getAlignment().getHeight() * av
1264 } while (ypos < totalHeight);
1266 pg.translate(idWidth, 0);
1268 getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1271 if ((pi * pheight) < totalHeight)
1273 return Printable.PAGE_EXISTS;
1278 return Printable.NO_SUCH_PAGE;
1283 * get current sequence ID panel width, or nominal value if panel were to be
1284 * displayed using default settings
1288 public int getVisibleIdWidth()
1290 return getVisibleIdWidth(true);
1294 * get current sequence ID panel width, or nominal value if panel were to be
1295 * displayed using default settings
1298 * indicate if the Id width for onscreen or offscreen display should
1302 public int getVisibleIdWidth(boolean onscreen)
1304 // see if rendering offscreen - check preferences and calc width accordingly
1305 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1307 return calculateIdWidth(-1).width + 4;
1309 Integer idwidth = null;
1311 || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1313 int w = getIdPanel().getWidth();
1314 return (w > 0 ? w : calculateIdWidth().width + 4);
1316 return idwidth.intValue() + 4;
1319 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1321 int boarderBottomOffset = 5;
1322 long pSessionId = System.currentTimeMillis();
1323 headless = (System.getProperty("java.awt.headless") != null && System
1324 .getProperty("java.awt.headless").equals("true"));
1325 if (alignFrame != null && !headless)
1329 alignFrame.setProgressBar(MessageManager.formatMessage(
1330 "status.saving_file", new Object[] { type.getLabel() }),
1336 AlignmentDimension aDimension = getAlignmentDimension();
1339 jalview.util.ImageMaker im;
1340 final String imageAction, imageTitle;
1341 if (type == jalview.util.ImageMaker.TYPE.PNG)
1343 imageAction = "Create PNG image from alignment";
1346 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1348 imageAction = "Create EPS file from alignment";
1349 imageTitle = alignFrame.getTitle();
1353 imageAction = "Create SVG file from alignment";
1354 imageTitle = alignFrame.getTitle();
1357 im = new jalview.util.ImageMaker(this, type, imageAction,
1358 aDimension.getWidth(), aDimension.getHeight()
1359 + boarderBottomOffset, file, imageTitle,
1360 alignFrame, pSessionId, headless);
1361 Graphics graphics = im.getGraphics();
1362 if (av.getWrapAlignment())
1364 if (graphics != null)
1366 printWrappedAlignment(aDimension.getWidth(),
1367 aDimension.getHeight() + boarderBottomOffset, 0,
1374 if (graphics != null)
1376 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1377 0, graphics, graphics);
1382 } catch (OutOfMemoryError err)
1385 System.out.println("########################\n" + "OUT OF MEMORY "
1386 + file + "\n" + "########################");
1387 new OOMWarning("Creating Image for " + file, err);
1388 // System.out.println("Create IMAGE: " + err);
1389 } catch (Exception ex)
1391 ex.printStackTrace();
1399 public AlignmentDimension getAlignmentDimension()
1401 int maxwidth = av.getAlignment().getWidth();
1402 if (av.hasHiddenColumns())
1404 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth);
1407 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1408 + getScalePanel().getHeight();
1409 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1411 if (av.getWrapAlignment())
1413 height = getWrappedHeight();
1416 // need to obtain default alignment width and then add in any
1417 // additional allowance for id margin
1418 // this duplicates the calculation in getWrappedHeight but adjusts for
1420 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1421 - alignFrame.getInsets().left
1422 - alignFrame.getInsets().right - getVisibleIdWidth()
1423 + getVisibleIdWidth(false);
1427 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1431 else if (av.isShowAnnotation())
1433 height += getAnnotationPanel().adjustPanelHeight() + 3;
1435 return new AlignmentDimension(width, height);
1442 public void makeEPS(File epsFile)
1444 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1450 public void makePNG(File pngFile)
1452 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1455 public void makeSVG(File svgFile)
1457 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1460 public void makePNGImageMap(File imgMapFile, String imageName)
1462 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1463 // ////////////////////////////////////////////
1464 int idWidth = getVisibleIdWidth(false);
1465 FontMetrics fm = getFontMetrics(av.getFont());
1466 int scaleHeight = av.getCharHeight() + fm.getDescent();
1469 // ////////////////////////////////
1470 if (imgMapFile != null)
1474 int s, sSize = av.getAlignment().getHeight(), res, alwidth = av
1475 .getAlignment().getWidth(), g, gSize, f, fSize, sy;
1476 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1477 out.println(jalview.io.HTMLOutput.getImageMapHTML());
1478 out.println("<img src=\"" + imageName
1479 + "\" border=\"0\" usemap=\"#Map\" >"
1480 + "<map name=\"Map\">");
1482 for (s = 0; s < sSize; s++)
1484 sy = s * av.getCharHeight() + scaleHeight;
1486 SequenceI seq = av.getAlignment().getSequenceAt(s);
1487 SequenceFeature[] features = seq.getSequenceFeatures();
1488 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1489 for (res = 0; res < alwidth; res++)
1491 StringBuilder text = new StringBuilder();
1492 String triplet = null;
1493 if (av.getAlignment().isNucleotide())
1495 triplet = ResidueProperties.nucleotideName.get(seq
1496 .getCharAt(res) + "");
1500 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(res)
1504 if (triplet == null)
1509 int alIndex = seq.findPosition(res);
1510 gSize = groups.length;
1511 for (g = 0; g < gSize; g++)
1513 if (text.length() < 1)
1515 text.append("<area shape=\"rect\" coords=\"")
1516 .append((idWidth + res * av.getCharWidth()))
1517 .append(",").append(sy).append(",")
1518 .append((idWidth + (res + 1) * av.getCharWidth()))
1519 .append(",").append((av.getCharHeight() + sy))
1520 .append("\"").append(" onMouseOver=\"toolTip('")
1521 .append(alIndex).append(" ").append(triplet);
1524 if (groups[g].getStartRes() < res
1525 && groups[g].getEndRes() > res)
1527 text.append("<br><em>").append(groups[g].getName())
1532 if (features != null)
1534 if (text.length() < 1)
1536 text.append("<area shape=\"rect\" coords=\"")
1537 .append((idWidth + res * av.getCharWidth()))
1538 .append(",").append(sy).append(",")
1539 .append((idWidth + (res + 1) * av.getCharWidth()))
1540 .append(",").append((av.getCharHeight() + sy))
1541 .append("\"").append(" onMouseOver=\"toolTip('")
1542 .append(alIndex).append(" ").append(triplet);
1544 fSize = features.length;
1545 for (f = 0; f < fSize; f++)
1548 if ((features[f].getBegin() <= seq.findPosition(res))
1549 && (features[f].getEnd() >= seq.findPosition(res)))
1551 if (features[f].isContactFeature())
1553 if (features[f].getBegin() == seq.findPosition(res)
1554 || features[f].getEnd() == seq
1557 text.append("<br>").append(features[f].getType())
1558 .append(" ").append(features[f].getBegin())
1559 .append(":").append(features[f].getEnd());
1564 text.append("<br>");
1565 text.append(features[f].getType());
1566 if (features[f].getDescription() != null
1567 && !features[f].getType().equals(
1568 features[f].getDescription()))
1570 text.append(" ").append(features[f].getDescription());
1573 if (features[f].getValue("status") != null)
1575 text.append(" (").append(features[f].getValue("status"))
1583 if (text.length() > 1)
1585 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1586 out.println(text.toString());
1590 out.println("</map></body></html>");
1593 } catch (Exception ex)
1595 ex.printStackTrace();
1597 } // /////////END OF IMAGE MAP
1601 int getWrappedHeight()
1603 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1605 if (System.getProperty("java.awt.headless") != null
1606 && System.getProperty("java.awt.headless").equals("true"))
1608 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1609 - vscroll.getPreferredSize().width
1610 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1613 int chunkWidth = getSeqPanel().seqCanvas
1614 .getWrappedCanvasWidth(seqPanelWidth);
1616 int hgap = av.getCharHeight();
1617 if (av.getScaleAboveWrapped())
1619 hgap += av.getCharHeight();
1622 int annotationHeight = 0;
1623 if (av.isShowAnnotation())
1625 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1628 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1631 int maxwidth = av.getAlignment().getWidth();
1632 if (av.hasHiddenColumns())
1634 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1637 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1643 * close the panel - deregisters all listeners and nulls any references to
1646 public void closePanel()
1648 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1649 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1650 PaintRefresher.RemoveComponent(this);
1655 * try to ensure references are nulled
1657 if (annotationPanel != null)
1659 annotationPanel.dispose();
1664 av.removePropertyChangeListener(propertyChangeListener);
1665 jalview.structure.StructureSelectionManager ssm = av
1666 .getStructureSelectionManager();
1667 ssm.removeStructureViewerListener(getSeqPanel(), null);
1668 ssm.removeSelectionListener(getSeqPanel());
1669 ssm.removeCommandListener(av);
1670 ssm.removeStructureViewerListener(getSeqPanel(), null);
1671 ssm.removeSelectionListener(getSeqPanel());
1677 if (Cache.log.isDebugEnabled())
1679 Cache.log.warn("Closing alignment panel which is already closed.");
1685 * Close any open dialogs that would be orphaned when this one is closed
1687 protected void closeChildFrames()
1689 if (calculationDialog != null)
1691 calculationDialog.closeFrame();
1696 * hides or shows dynamic annotation rows based on groups and av state flags
1698 public void updateAnnotation()
1700 updateAnnotation(false, false);
1703 public void updateAnnotation(boolean applyGlobalSettings)
1705 updateAnnotation(applyGlobalSettings, false);
1708 public void updateAnnotation(boolean applyGlobalSettings,
1709 boolean preserveNewGroupSettings)
1711 av.updateGroupAnnotationSettings(applyGlobalSettings,
1712 preserveNewGroupSettings);
1713 adjustAnnotationHeight();
1717 public AlignmentI getAlignment()
1719 return av == null ? null : av.getAlignment();
1723 public String getViewName()
1729 * Make/Unmake this alignment panel the current input focus
1733 public void setSelected(boolean b)
1737 if (alignFrame.getSplitViewContainer() != null)
1740 * bring enclosing SplitFrame to front first if there is one
1742 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1744 alignFrame.setSelected(b);
1745 } catch (Exception ex)
1751 alignFrame.setDisplayedView(this);
1756 public StructureSelectionManager getStructureSelectionManager()
1758 return av.getStructureSelectionManager();
1762 public void raiseOOMWarning(String string, OutOfMemoryError error)
1764 new OOMWarning(string, error, this);
1768 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1771 return new FeatureRenderer(this);
1775 public jalview.api.FeatureRenderer getFeatureRenderer()
1777 return seqPanel.seqCanvas.getFeatureRenderer();
1780 public void updateFeatureRenderer(
1781 jalview.renderer.seqfeatures.FeatureRenderer fr)
1783 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1786 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1788 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1790 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1794 public ScalePanel getScalePanel()
1799 public void setScalePanel(ScalePanel scalePanel)
1801 this.scalePanel = scalePanel;
1804 public SeqPanel getSeqPanel()
1809 public void setSeqPanel(SeqPanel seqPanel)
1811 this.seqPanel = seqPanel;
1814 public AnnotationPanel getAnnotationPanel()
1816 return annotationPanel;
1819 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1821 this.annotationPanel = annotationPanel;
1824 public AnnotationLabels getAlabels()
1829 public void setAlabels(AnnotationLabels alabels)
1831 this.alabels = alabels;
1834 public IdPanel getIdPanel()
1839 public void setIdPanel(IdPanel idPanel)
1841 this.idPanel = idPanel;
1845 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1846 * The aim is to keep the two alignments 'lined up' on their centre columns.
1849 * holds mapped region(s) of this alignment that we are scrolling
1850 * 'to'; may be modified for sequence offset by this method
1851 * @param verticalOffset
1852 * the number of visible sequences to show above the mapped region
1854 public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1857 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1858 * mapped), we can make the scroll-to location a sequence above the one
1861 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1862 List<SequenceI> seqs = av.getAlignment().getSequences();
1865 * This is like AlignmentI.findIndex(seq) but here we are matching the
1866 * dataset sequence not the aligned sequence
1868 boolean matched = false;
1869 for (SequenceI seq : seqs)
1871 if (mappedTo == seq.getDatasetSequence())
1879 return; // failsafe, shouldn't happen
1883 * Scroll to position but centring the target residue.
1885 scrollToPosition(sr, verticalOffset, true, true);
1889 * Set a flag to say do not scroll any (cDNA/protein) complement.
1893 protected void setDontScrollComplement(boolean b)
1895 this.dontScrollComplement = b;
1898 protected boolean isDontScrollComplement()
1900 return this.dontScrollComplement;
1906 * @adjustHeight if true, try to recalculate panel height for visible
1909 protected void refresh(boolean adjustHeight)
1911 validateAnnotationDimensions(adjustHeight);
1915 // sort, repaint, update overview
1916 paintAlignment(true);
1920 // lightweight repaint
1926 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1927 * reference should be nulled when the dialog is closed.
1929 * @param calculationChooser
1931 public void setCalculationDialog(CalculationChooser calculationChooser)
1933 calculationDialog = calculationChooser;
1937 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1940 public CalculationChooser getCalculationDialog()
1942 return calculationDialog;