2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AnnotationSorter;
24 import jalview.api.AlignViewportI;
25 import jalview.api.AlignmentViewPanel;
26 import jalview.bin.Cache;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.HiddenColumns;
29 import jalview.datamodel.SearchResultsI;
30 import jalview.datamodel.SequenceFeature;
31 import jalview.datamodel.SequenceGroup;
32 import jalview.datamodel.SequenceI;
33 import jalview.io.HTMLOutput;
34 import jalview.jbgui.GAlignmentPanel;
35 import jalview.math.AlignmentDimension;
36 import jalview.schemes.ResidueProperties;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.util.Comparison;
39 import jalview.util.MessageManager;
40 import jalview.util.Platform;
41 import jalview.viewmodel.ViewportListenerI;
42 import jalview.viewmodel.ViewportRanges;
44 import java.awt.BorderLayout;
45 import java.awt.Color;
46 import java.awt.Container;
47 import java.awt.Dimension;
49 import java.awt.FontMetrics;
50 import java.awt.Graphics;
51 import java.awt.Insets;
52 import java.awt.event.AdjustmentEvent;
53 import java.awt.event.AdjustmentListener;
54 import java.awt.event.ComponentAdapter;
55 import java.awt.event.ComponentEvent;
56 import java.awt.print.PageFormat;
57 import java.awt.print.Printable;
58 import java.awt.print.PrinterException;
59 import java.beans.PropertyChangeEvent;
60 import java.beans.PropertyChangeListener;
62 import java.io.FileWriter;
63 import java.io.PrintWriter;
64 import java.util.List;
66 import javax.swing.SwingUtilities;
72 * @version $Revision: 1.161 $
74 public class AlignmentPanel extends GAlignmentPanel implements
75 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
77 public AlignViewport av;
79 OverviewPanel overviewPanel;
81 private SeqPanel seqPanel;
83 private IdPanel idPanel;
85 private boolean headless;
87 IdwidthAdjuster idwidthAdjuster;
90 public AlignFrame alignFrame;
92 private ScalePanel scalePanel;
94 private AnnotationPanel annotationPanel;
96 private AnnotationLabels alabels;
98 private int hextent = 0;
100 private int vextent = 0;
103 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
104 * false, suppresses invoking the same method recursively.
106 private boolean scrollComplementaryPanel = true;
108 private PropertyChangeListener propertyChangeListener;
110 private CalculationChooser calculationDialog;
113 * Creates a new AlignmentPanel object.
118 public AlignmentPanel(AlignFrame af, final AlignViewport av)
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 addComponentListener(new ComponentAdapter()
148 public void componentResized(ComponentEvent evt)
150 // reset the viewport ranges when the alignment panel is resized
151 // in particular, this initialises the end residue value when Jalview
153 ViewportRanges ranges = av.getRanges();
154 if (av.getWrapAlignment())
156 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
157 getSeqPanel().seqCanvas.getWidth());
158 ranges.setViewportWidth(widthInRes);
162 int widthInRes = getSeqPanel().seqCanvas.getWidth()
164 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
165 / av.getCharHeight();
167 ranges.setViewportWidth(widthInRes);
168 ranges.setViewportHeight(heightInSeq);
174 final AlignmentPanel ap = this;
175 propertyChangeListener = new PropertyChangeListener()
178 public void propertyChange(PropertyChangeEvent evt)
180 if (evt.getPropertyName().equals("alignment"))
182 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
187 av.addPropertyChangeListener(propertyChangeListener);
189 av.getRanges().addPropertyChangeListener(this);
191 adjustAnnotationHeight();
196 public AlignViewportI getAlignViewport()
201 public void alignmentChanged()
203 av.alignmentChanged(this);
205 if (getCalculationDialog() != null)
207 getCalculationDialog().validateCalcTypes();
210 alignFrame.updateEditMenuBar();
212 // no idea if we need to update structure
213 paintAlignment(true, true);
220 public void fontChanged()
222 // set idCanvas bufferedImage to null
223 // to prevent drawing old image
224 FontMetrics fm = getFontMetrics(av.getFont());
226 scalePanelHolder.setPreferredSize(
227 new Dimension(10, av.getCharHeight() + fm.getDescent()));
228 idSpaceFillerPanel1.setPreferredSize(
229 new Dimension(10, av.getCharHeight() + fm.getDescent()));
230 idwidthAdjuster.invalidate();
231 scalePanelHolder.invalidate();
232 getIdPanel().getIdCanvas().gg = null;
233 getSeqPanel().seqCanvas.img = null;
234 getAnnotationPanel().adjustPanelHeight();
236 Dimension d = calculateIdWidth();
238 d.setSize(d.width + 4, d.height);
239 getIdPanel().getIdCanvas().setPreferredSize(d);
240 hscrollFillerPanel.setPreferredSize(d);
246 * Calculate the width of the alignment labels based on the displayed names
247 * and any bounds on label width set in preferences.
249 * @return Dimension giving the maximum width of the alignment label panel
250 * that should be used.
252 public Dimension calculateIdWidth()
254 // calculate sensible default width when no preference is available
256 if (av.getIdWidth() < 0)
258 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
259 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
260 r = calculateIdWidth(maxwidth);
261 av.setIdWidth(r.width);
266 r.width = av.getIdWidth();
273 * Calculate the width of the alignment labels based on the displayed names
274 * and any bounds on label width set in preferences.
277 * -1 or maximum width allowed for IdWidth
278 * @return Dimension giving the maximum width of the alignment label panel
279 * that should be used.
281 public Dimension calculateIdWidth(int maxwidth)
283 Container c = new Container();
285 FontMetrics fm = c.getFontMetrics(
286 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
288 AlignmentI al = av.getAlignment();
293 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
295 SequenceI s = al.getSequenceAt(i);
297 id = s.getDisplayId(av.getShowJVSuffix());
299 if (fm.stringWidth(id) > idWidth)
301 idWidth = fm.stringWidth(id);
307 // Also check annotation label widths
310 if (al.getAlignmentAnnotation() != null)
312 fm = c.getFontMetrics(getAlabels().getFont());
314 while (i < al.getAlignmentAnnotation().length)
316 String label = al.getAlignmentAnnotation()[i].label;
318 if (fm.stringWidth(label) > idWidth)
320 idWidth = fm.stringWidth(label);
327 return new Dimension(
328 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
332 * Highlight the given results on the alignment.
335 public void highlightSearchResults(SearchResultsI results)
337 boolean scrolled = scrollToPosition(results, 0, true, false);
339 boolean noFastPaint = scrolled && av.getWrapAlignment();
341 getSeqPanel().seqCanvas.highlightSearchResults(results, noFastPaint);
345 * Scroll the view to show the position of the highlighted region in results
348 * @param searchResults
349 * @param redrawOverview
352 public boolean scrollToPosition(SearchResultsI searchResults,
353 boolean redrawOverview)
355 return scrollToPosition(searchResults, 0, redrawOverview, false);
359 * Scrolls the view (if necessary) to show the position of the first
360 * highlighted region in results (if any). Answers true if the view was
361 * scrolled, or false if no matched region was found, or it is already
365 * @param verticalOffset
366 * if greater than zero, allows scrolling to a position below the
367 * first displayed sequence
368 * @param redrawOverview
369 * - when set, the overview will be recalculated (takes longer)
371 * if true, try to centre the search results horizontally in the view
374 protected boolean scrollToPosition(SearchResultsI results,
375 int verticalOffset, boolean redrawOverview, boolean centre)
377 int startv, endv, starts, ends;
378 ViewportRanges ranges = av.getRanges();
380 if (results == null || results.isEmpty() || av == null
381 || av.getAlignment() == null)
385 int seqIndex = av.getAlignment().findIndex(results);
390 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
392 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
401 * To centre results, scroll to positions half the visible width
402 * left/right of the start/end positions
406 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
407 start = Math.max(start - offset, 0);
408 end = end + offset - 1;
414 if (end == seq.getEnd())
419 if (av.hasHiddenColumns())
421 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
422 start = hidden.findColumnPosition(start);
423 end = hidden.findColumnPosition(end);
426 if (!hidden.isVisible(r[0]))
428 // don't scroll - position isn't visible
435 * allow for offset of target sequence (actually scroll to one above it)
437 seqIndex = Math.max(0, seqIndex - verticalOffset);
438 boolean scrollNeeded = true;
440 if (!av.getWrapAlignment())
442 if ((startv = ranges.getStartRes()) >= start)
445 * Scroll left to make start of search results visible
447 setScrollValues(start, seqIndex);
449 else if ((endv = ranges.getEndRes()) <= end)
452 * Scroll right to make end of search results visible
454 setScrollValues(startv + end - endv, seqIndex);
456 else if ((starts = ranges.getStartSeq()) > seqIndex)
459 * Scroll up to make start of search results visible
461 setScrollValues(ranges.getStartRes(), seqIndex);
463 else if ((ends = ranges.getEndSeq()) <= seqIndex)
466 * Scroll down to make end of search results visible
468 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
472 * Else results are already visible - no need to scroll
474 scrollNeeded = false;
478 scrollNeeded = ranges.scrollToWrappedVisible(start);
481 paintAlignment(redrawOverview, false);
489 * @return DOCUMENT ME!
491 public OverviewPanel getOverviewPanel()
493 return overviewPanel;
502 public void setOverviewPanel(OverviewPanel op)
510 * Hide or show annotation panel
513 public void setAnnotationVisible(boolean b)
515 if (!av.getWrapAlignment())
517 annotationSpaceFillerHolder.setVisible(b);
518 annotationScroller.setVisible(b);
524 * automatically adjust annotation panel height for new annotation whilst
525 * ensuring the alignment is still visible.
528 public void adjustAnnotationHeight()
530 // TODO: display vertical annotation scrollbar if necessary
531 // this is called after loading new annotation onto alignment
532 if (alignFrame.getHeight() == 0)
534 System.out.println("NEEDS FIXING");
536 validateAnnotationDimensions(true);
538 // TODO: many places call this method and also paintAlignment with various
539 // different settings. this means multiple redraws are triggered...
540 paintAlignment(true, false);
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,
574 availableHeight - 2 * rowHeight);
579 // maintain same window layout whilst updating sliders
580 annotationHeight = annotationScroller.getSize().height;
584 annotationScroller.setPreferredSize(
585 new Dimension(annotationScroller.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 ViewportRanges ranges = av.getRanges();
608 ranges.setStartSeq(0);
609 scalePanelHolder.setVisible(!wrap);
610 hscroll.setVisible(!wrap);
611 idwidthAdjuster.setVisible(!wrap);
615 annotationScroller.setVisible(false);
616 annotationSpaceFillerHolder.setVisible(false);
618 else if (av.isShowAnnotation())
620 annotationScroller.setVisible(true);
621 annotationSpaceFillerHolder.setVisible(true);
624 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
626 { // may not yet be laid out
629 int widthInRes = getSeqPanel().seqCanvas
630 .getWrappedCanvasWidth(canvasWidth);
631 ranges.setViewportWidth(widthInRes);
635 int widthInRes = (canvasWidth / av.getCharWidth());
636 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
637 / av.getCharHeight());
639 ranges.setViewportWidth(widthInRes);
640 ranges.setViewportHeight(heightInSeq);
644 idSpaceFillerPanel1.setVisible(!wrap);
650 * Adjust row/column scrollers to show a visible position in the alignment.
653 * visible column to scroll to
655 * visible row to scroll to
658 public void setScrollValues(int xpos, int ypos)
663 if (av == null || av.getAlignment() == null)
668 if (av.getWrapAlignment())
670 setScrollingForWrappedPanel(x);
674 int width = av.getAlignment().getWidth();
675 int height = av.getAlignment().getHeight();
677 if (av.hasHiddenColumns())
679 // reset the width to exclude hidden columns
680 width = av.getAlignment().getHiddenColumns()
681 .findColumnPosition(width);
684 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
685 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
692 if (vextent > height)
697 if ((hextent + x) > width)
702 if ((vextent + y) > height)
704 y = height - vextent;
717 // update the scroll values
718 hscroll.setValues(x, hextent, 0, width);
719 vscroll.setValues(y, vextent, 0, height);
724 * Respond to adjustment event when horizontal or vertical scrollbar is
728 * adjustment event encoding whether hscroll or vscroll changed
731 public void adjustmentValueChanged(AdjustmentEvent evt)
733 if (av.getWrapAlignment())
735 adjustScrollingWrapped(evt);
739 ViewportRanges ranges = av.getRanges();
741 if (evt.getSource() == hscroll)
743 int oldX = ranges.getStartRes();
744 int oldwidth = ranges.getViewportWidth();
745 int x = hscroll.getValue();
746 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
748 // if we're scrolling to the position we're already at, stop
749 // this prevents infinite recursion of events when the scroll/viewport
750 // ranges values are the same
751 if ((x == oldX) && (width == oldwidth))
755 ranges.setViewportStartAndWidth(x, width);
757 else if (evt.getSource() == vscroll)
759 int oldY = ranges.getStartSeq();
760 int oldheight = ranges.getViewportHeight();
761 int y = vscroll.getValue();
762 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
764 // if we're scrolling to the position we're already at, stop
765 // this prevents infinite recursion of events when the scroll/viewport
766 // ranges values are the same
767 if ((y == oldY) && (height == oldheight))
771 ranges.setViewportStartAndHeight(y, height);
777 * Responds to a scroll change by setting the start position of the viewport.
782 protected void adjustScrollingWrapped(AdjustmentEvent evt)
784 if (evt.getSource() == hscroll)
786 return; // no horizontal scroll when wrapped
788 final ViewportRanges ranges = av.getRanges();
790 if (evt.getSource() == vscroll)
792 int newY = vscroll.getValue();
795 * if we're scrolling to the position we're already at, stop
796 * this prevents infinite recursion of events when the scroll/viewport
797 * ranges values are the same
799 int oldX = ranges.getStartRes();
800 int oldY = ranges.getWrappedScrollPosition(oldX);
808 * limit page up/down to one width's worth of positions
810 int rowSize = ranges.getViewportWidth();
811 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
812 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
817 // This is only called if file loaded is a jar file that
818 // was wrapped when saved and user has wrap alignment true
819 // as preference setting
820 SwingUtilities.invokeLater(new Runnable()
825 // When updating scrolling to use ViewportChange events, this code
826 // could not be validated and it is not clear if it is now being
827 // called. Log warning here in case it is called and unforeseen
830 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
832 // scroll to start of panel
833 ranges.setStartRes(0);
834 ranges.setStartSeq(0);
842 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
845 public void paintAlignment(boolean updateOverview,
846 boolean updateStructures)
848 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
849 av.isShowAutocalculatedAbove());
850 sorter.sort(getAlignment().getAlignmentAnnotation(),
851 av.getSortAnnotationsBy());
854 if (updateStructures)
856 av.getStructureSelectionManager().sequenceColoursChanged(this);
861 if (overviewPanel != null)
863 overviewPanel.updateOverviewImage();
875 public void paintComponent(Graphics g)
879 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
880 idPanelHolder.setPreferredSize(d);
881 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
885 * set scroll bar positions
887 ViewportRanges ranges = av.getRanges();
888 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
892 * Set vertical scroll bar position, and number of increments, for wrapped
895 * @param topLeftColumn
896 * the column position at top left (0..)
898 private void setScrollingForWrappedPanel(int topLeftColumn)
900 ViewportRanges ranges = av.getRanges();
901 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
902 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
905 * a scrollbar's value can be set to at most (maximum-extent)
906 * so we add extent (1) to the maxScroll value
908 vscroll.setUnitIncrement(1);
909 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
922 * @return DOCUMENT ME!
924 * @throws PrinterException
928 public int print(Graphics pg, PageFormat pf, int pi)
929 throws PrinterException
931 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
933 int pwidth = (int) pf.getImageableWidth();
934 int pheight = (int) pf.getImageableHeight();
936 if (av.getWrapAlignment())
938 return printWrappedAlignment(pwidth, pheight, pi, pg);
942 return printUnwrapped(pwidth, pheight, pi, pg, pg);
958 * @return DOCUMENT ME!
960 * @throws PrinterException
964 * Draws the alignment image, including sequence ids, sequences, and
965 * annotation labels and annotations if shown, on either one or two Graphics
972 * the graphics context for sequence ids and annotation labels
973 * @param alignmentGraphics
974 * the graphics context for sequences and annotations (may or may not
975 * be the same context as idGraphics)
977 * @throws PrinterException
979 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
980 Graphics idGraphics, Graphics alignmentGraphics)
981 throws PrinterException
983 final int idWidth = getVisibleIdWidth(false);
986 * Get the horizontal offset to where we draw the sequences.
987 * This is idWidth if using a single Graphics context, else zero.
989 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
992 FontMetrics fm = getFontMetrics(av.getFont());
993 int charHeight = av.getCharHeight();
994 int scaleHeight = charHeight + fm.getDescent();
996 idGraphics.setColor(Color.white);
997 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
998 idGraphics.setFont(av.getFont());
1001 * How many sequences and residues can we fit on a printable page?
1003 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1005 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1007 int alignmentWidth = av.getAlignment().getWidth();
1008 int pagesWide = (alignmentWidth / totalRes) + 1;
1010 final int startRes = (pi % pagesWide) * totalRes;
1011 int endRes = (startRes + totalRes) - 1;
1013 if (endRes > (alignmentWidth - 1))
1015 endRes = alignmentWidth - 1;
1018 final int startSeq = (pi / pagesWide) * totalSeq;
1019 int endSeq = startSeq + totalSeq;
1021 int alignmentHeight = av.getAlignment().getHeight();
1022 if (endSeq > alignmentHeight)
1024 endSeq = alignmentHeight;
1027 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1029 if (av.isShowAnnotation())
1031 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1034 pagesHigh /= pageHeight;
1036 if (pi >= (pagesWide * pagesHigh))
1038 return Printable.NO_SUCH_PAGE;
1040 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1043 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1045 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1046 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1047 pageWidth - idWidth, scaleHeight);
1048 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1051 * Draw the sequence ids, offset for scale height,
1052 * then reset to top left (0, 0)
1054 idGraphics.translate(0, scaleHeight);
1055 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1056 Color currentColor = null;
1057 Color currentTextColor = null;
1060 for (int i = startSeq; i < endSeq; i++)
1062 seq = av.getAlignment().getSequenceAt(i);
1063 if ((av.getSelectionGroup() != null)
1064 && av.getSelectionGroup().getSequences(null).contains(seq))
1067 * gray out ids of sequences in selection group (if any)
1069 currentColor = Color.gray;
1070 currentTextColor = Color.black;
1074 currentColor = av.getSequenceColour(seq);
1075 currentTextColor = Color.black;
1078 idGraphics.setColor(currentColor);
1079 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1082 idGraphics.setColor(currentTextColor);
1085 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1086 if (av.isRightAlignIds())
1088 fm = idGraphics.getFontMetrics();
1089 xPos = idWidth - fm.stringWidth(displayId) - 4;
1092 idGraphics.drawString(displayId, xPos,
1093 (((i - startSeq) * charHeight) + charHeight)
1094 - (charHeight / 5));
1096 idGraphics.setFont(av.getFont());
1097 idGraphics.translate(0, -scaleHeight);
1100 * draw the sequences, offset for scale height, and id width (if using a
1101 * single graphics context), then reset to (0, scale height)
1103 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1104 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1105 endRes, startSeq, endSeq);
1106 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1108 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1111 * draw annotation labels; drawComponent() translates by
1112 * getScrollOffset(), so compensate for that first;
1113 * then reset to (0, scale height)
1115 int offset = getAlabels().getScrollOffset();
1116 idGraphics.translate(0, -offset);
1117 idGraphics.translate(0, alignmentDrawnHeight);
1118 getAlabels().drawComponent(idGraphics, idWidth);
1119 idGraphics.translate(0, -alignmentDrawnHeight);
1122 * draw the annotations starting at
1123 * (idOffset, alignmentHeight) from (0, scaleHeight)
1125 alignmentGraphics.translate(alignmentGraphicsOffset,
1126 alignmentDrawnHeight);
1127 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1128 alignmentGraphics, -1, startRes, endRes + 1);
1131 return Printable.PAGE_EXISTS;
1146 * @return DOCUMENT ME!
1148 * @throws PrinterException
1151 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1152 Graphics pg) throws PrinterException
1154 int annotationHeight = 0;
1155 AnnotationLabels labels = null;
1156 if (av.isShowAnnotation())
1158 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1159 labels = new AnnotationLabels(av);
1162 int hgap = av.getCharHeight();
1163 if (av.getScaleAboveWrapped())
1165 hgap += av.getCharHeight();
1168 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1171 int idWidth = getVisibleIdWidth(false);
1173 int maxwidth = av.getAlignment().getWidth();
1174 if (av.hasHiddenColumns())
1176 maxwidth = av.getAlignment().getHiddenColumns()
1177 .findColumnPosition(maxwidth) - 1;
1180 int resWidth = getSeqPanel().seqCanvas
1181 .getWrappedCanvasWidth(pwidth - idWidth);
1183 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1185 pg.setColor(Color.white);
1186 pg.fillRect(0, 0, pwidth, pheight);
1187 pg.setFont(av.getFont());
1191 pg.setColor(Color.black);
1193 pg.translate(0, -pi * pheight);
1195 pg.setClip(0, pi * pheight, pwidth, pheight);
1201 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1203 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1204 SequenceI s = av.getAlignment().getSequenceAt(i);
1205 String string = s.getDisplayId(av.getShowJVSuffix());
1207 if (av.isRightAlignIds())
1209 FontMetrics fm = pg.getFontMetrics();
1210 xPos = idWidth - fm.stringWidth(string) - 4;
1212 pg.drawString(string, xPos,
1213 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1214 - (av.getCharHeight() / 5));
1218 pg.translate(-3, ypos
1219 + (av.getAlignment().getHeight() * av.getCharHeight()));
1221 pg.setFont(av.getFont());
1222 labels.drawComponent(pg, idWidth);
1223 pg.translate(+3, -ypos
1224 - (av.getAlignment().getHeight() * av.getCharHeight()));
1228 } while (ypos < totalHeight);
1230 pg.translate(idWidth, 0);
1232 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(pg, pwidth - idWidth,
1235 if ((pi * pheight) < totalHeight)
1237 return Printable.PAGE_EXISTS;
1242 return Printable.NO_SUCH_PAGE;
1247 * get current sequence ID panel width, or nominal value if panel were to be
1248 * displayed using default settings
1252 public int getVisibleIdWidth()
1254 return getVisibleIdWidth(true);
1258 * get current sequence ID panel width, or nominal value if panel were to be
1259 * displayed using default settings
1262 * indicate if the Id width for onscreen or offscreen display should
1266 public int getVisibleIdWidth(boolean onscreen)
1268 // see if rendering offscreen - check preferences and calc width accordingly
1269 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1271 return calculateIdWidth(-1).width + 4;
1273 Integer idwidth = null;
1274 if (onscreen || (idwidth = Cache
1275 .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1277 int w = getIdPanel().getWidth();
1278 return (w > 0 ? w : calculateIdWidth().width + 4);
1280 return idwidth.intValue() + 4;
1283 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1285 int boarderBottomOffset = 5;
1286 long pSessionId = System.currentTimeMillis();
1287 headless = (System.getProperty("java.awt.headless") != null
1288 && System.getProperty("java.awt.headless").equals("true"));
1289 if (alignFrame != null && !headless)
1293 alignFrame.setProgressBar(MessageManager
1294 .formatMessage("status.saving_file", new Object[]
1295 { type.getLabel() }), pSessionId);
1300 AlignmentDimension aDimension = getAlignmentDimension();
1303 jalview.util.ImageMaker im;
1304 final String imageAction, imageTitle;
1305 if (type == jalview.util.ImageMaker.TYPE.PNG)
1307 imageAction = "Create PNG image from alignment";
1310 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1312 imageAction = "Create EPS file from alignment";
1313 imageTitle = alignFrame.getTitle();
1317 imageAction = "Create SVG file from alignment";
1318 imageTitle = alignFrame.getTitle();
1321 im = new jalview.util.ImageMaker(this, type, imageAction,
1322 aDimension.getWidth(),
1323 aDimension.getHeight() + boarderBottomOffset, file,
1324 imageTitle, alignFrame, pSessionId, headless);
1325 Graphics graphics = im.getGraphics();
1326 if (av.getWrapAlignment())
1328 if (graphics != null)
1330 printWrappedAlignment(aDimension.getWidth(),
1331 aDimension.getHeight() + boarderBottomOffset, 0,
1338 if (graphics != null)
1340 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1341 graphics, graphics);
1346 } catch (OutOfMemoryError err)
1349 System.out.println("########################\n" + "OUT OF MEMORY "
1350 + file + "\n" + "########################");
1351 new OOMWarning("Creating Image for " + file, err);
1352 // System.out.println("Create IMAGE: " + err);
1353 } catch (Exception ex)
1355 ex.printStackTrace();
1363 public AlignmentDimension getAlignmentDimension()
1365 int maxwidth = av.getAlignment().getWidth();
1366 if (av.hasHiddenColumns())
1368 maxwidth = av.getAlignment().getHiddenColumns()
1369 .findColumnPosition(maxwidth);
1372 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1373 + getScalePanel().getHeight();
1374 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1376 if (av.getWrapAlignment())
1378 height = getWrappedHeight();
1381 // need to obtain default alignment width and then add in any
1382 // additional allowance for id margin
1383 // this duplicates the calculation in getWrappedHeight but adjusts for
1385 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1386 - alignFrame.getInsets().left - alignFrame.getInsets().right
1387 - getVisibleIdWidth() + getVisibleIdWidth(false);
1391 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1395 else if (av.isShowAnnotation())
1397 height += getAnnotationPanel().adjustPanelHeight() + 3;
1399 return new AlignmentDimension(width, height);
1406 public void makeEPS(File epsFile)
1408 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1414 public void makePNG(File pngFile)
1416 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1419 public void makeSVG(File svgFile)
1421 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1424 public void makePNGImageMap(File imgMapFile, String imageName)
1426 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1427 // ////////////////////////////////////////////
1428 int idWidth = getVisibleIdWidth(false);
1429 FontMetrics fm = getFontMetrics(av.getFont());
1430 int scaleHeight = av.getCharHeight() + fm.getDescent();
1433 // ////////////////////////////////
1434 if (imgMapFile != null)
1438 int sSize = av.getAlignment().getHeight();
1439 int alwidth = av.getAlignment().getWidth();
1440 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1441 out.println(HTMLOutput.getImageMapHTML());
1442 out.println("<img src=\"" + imageName
1443 + "\" border=\"0\" usemap=\"#Map\" >"
1444 + "<map name=\"Map\">");
1446 for (int s = 0; s < sSize; s++)
1448 int sy = s * av.getCharHeight() + scaleHeight;
1450 SequenceI seq = av.getAlignment().getSequenceAt(s);
1451 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1452 for (int column = 0; column < alwidth; column++)
1454 StringBuilder text = new StringBuilder(512);
1455 String triplet = null;
1456 if (av.getAlignment().isNucleotide())
1458 triplet = ResidueProperties.nucleotideName.get(seq
1459 .getCharAt(column) + "");
1463 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1467 if (triplet == null)
1472 int seqPos = seq.findPosition(column);
1473 int gSize = groups.length;
1474 for (int g = 0; g < gSize; g++)
1476 if (text.length() < 1)
1478 text.append("<area shape=\"rect\" coords=\"")
1479 .append((idWidth + column * av.getCharWidth()))
1480 .append(",").append(sy).append(",")
1481 .append((idWidth + (column + 1) * av.getCharWidth()))
1482 .append(",").append((av.getCharHeight() + sy))
1483 .append("\"").append(" onMouseOver=\"toolTip('")
1484 .append(seqPos).append(" ").append(triplet);
1487 if (groups[g].getStartRes() < column
1488 && groups[g].getEndRes() > column)
1490 text.append("<br><em>").append(groups[g].getName())
1495 if (text.length() < 1)
1497 text.append("<area shape=\"rect\" coords=\"")
1498 .append((idWidth + column * av.getCharWidth()))
1499 .append(",").append(sy).append(",")
1500 .append((idWidth + (column + 1) * av.getCharWidth()))
1501 .append(",").append((av.getCharHeight() + sy))
1502 .append("\"").append(" onMouseOver=\"toolTip('")
1503 .append(seqPos).append(" ").append(triplet);
1505 if (!Comparison.isGap(seq.getCharAt(column)))
1507 List<SequenceFeature> features = seq.findFeatures(column, column);
1508 for (SequenceFeature sf : features)
1510 if (sf.isContactFeature())
1512 text.append("<br>").append(sf.getType()).append(" ")
1513 .append(sf.getBegin()).append(":")
1514 .append(sf.getEnd());
1518 text.append("<br>");
1519 text.append(sf.getType());
1520 String description = sf.getDescription();
1521 if (description != null
1522 && !sf.getType().equals(description))
1524 description = description.replace("\"", """);
1525 text.append(" ").append(description);
1528 String status = sf.getStatus();
1529 if (status != null && !"".equals(status))
1531 text.append(" (").append(status).append(")");
1534 if (text.length() > 1)
1536 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1537 out.println(text.toString());
1542 out.println("</map></body></html>");
1545 } catch (Exception ex)
1547 ex.printStackTrace();
1549 } // /////////END OF IMAGE MAP
1553 int getWrappedHeight()
1555 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1557 if (System.getProperty("java.awt.headless") != null
1558 && System.getProperty("java.awt.headless").equals("true"))
1560 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1561 - vscroll.getPreferredSize().width
1562 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1565 int chunkWidth = getSeqPanel().seqCanvas
1566 .getWrappedCanvasWidth(seqPanelWidth);
1568 int hgap = av.getCharHeight();
1569 if (av.getScaleAboveWrapped())
1571 hgap += av.getCharHeight();
1574 int annotationHeight = 0;
1575 if (av.isShowAnnotation())
1577 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1580 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1583 int maxwidth = av.getAlignment().getWidth();
1584 if (av.hasHiddenColumns())
1586 maxwidth = av.getAlignment().getHiddenColumns()
1587 .findColumnPosition(maxwidth) - 1;
1590 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1596 * close the panel - deregisters all listeners and nulls any references to
1599 public void closePanel()
1601 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1602 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1603 PaintRefresher.RemoveComponent(this);
1608 * try to ensure references are nulled
1610 if (annotationPanel != null)
1612 annotationPanel.dispose();
1613 annotationPanel = null;
1618 av.removePropertyChangeListener(propertyChangeListener);
1619 propertyChangeListener = null;
1620 StructureSelectionManager ssm = av.getStructureSelectionManager();
1621 ssm.removeStructureViewerListener(getSeqPanel(), null);
1622 ssm.removeSelectionListener(getSeqPanel());
1623 ssm.removeCommandListener(av);
1624 ssm.removeStructureViewerListener(getSeqPanel(), null);
1625 ssm.removeSelectionListener(getSeqPanel());
1631 if (Cache.log.isDebugEnabled())
1633 Cache.log.warn("Closing alignment panel which is already closed.");
1639 * Close any open dialogs that would be orphaned when this one is closed
1641 protected void closeChildFrames()
1643 if (overviewPanel != null)
1645 overviewPanel.dispose();
1646 overviewPanel = null;
1648 if (calculationDialog != null)
1650 calculationDialog.closeFrame();
1651 calculationDialog = null;
1656 * hides or shows dynamic annotation rows based on groups and av state flags
1658 public void updateAnnotation()
1660 updateAnnotation(false, false);
1663 public void updateAnnotation(boolean applyGlobalSettings)
1665 updateAnnotation(applyGlobalSettings, false);
1668 public void updateAnnotation(boolean applyGlobalSettings,
1669 boolean preserveNewGroupSettings)
1671 av.updateGroupAnnotationSettings(applyGlobalSettings,
1672 preserveNewGroupSettings);
1673 adjustAnnotationHeight();
1677 public AlignmentI getAlignment()
1679 return av == null ? null : av.getAlignment();
1683 public String getViewName()
1689 * Make/Unmake this alignment panel the current input focus
1693 public void setSelected(boolean b)
1697 if (alignFrame.getSplitViewContainer() != null)
1700 * bring enclosing SplitFrame to front first if there is one
1702 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1704 alignFrame.setSelected(b);
1705 } catch (Exception ex)
1711 alignFrame.setDisplayedView(this);
1716 public StructureSelectionManager getStructureSelectionManager()
1718 return av.getStructureSelectionManager();
1722 public void raiseOOMWarning(String string, OutOfMemoryError error)
1724 new OOMWarning(string, error, this);
1728 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1731 return new FeatureRenderer(this);
1735 public jalview.api.FeatureRenderer getFeatureRenderer()
1737 return seqPanel.seqCanvas.getFeatureRenderer();
1740 public void updateFeatureRenderer(
1741 jalview.renderer.seqfeatures.FeatureRenderer fr)
1743 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1746 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1748 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1750 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1754 public ScalePanel getScalePanel()
1759 public void setScalePanel(ScalePanel scalePanel)
1761 this.scalePanel = scalePanel;
1764 public SeqPanel getSeqPanel()
1769 public void setSeqPanel(SeqPanel seqPanel)
1771 this.seqPanel = seqPanel;
1774 public AnnotationPanel getAnnotationPanel()
1776 return annotationPanel;
1779 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1781 this.annotationPanel = annotationPanel;
1784 public AnnotationLabels getAlabels()
1789 public void setAlabels(AnnotationLabels alabels)
1791 this.alabels = alabels;
1794 public IdPanel getIdPanel()
1799 public void setIdPanel(IdPanel idPanel)
1801 this.idPanel = idPanel;
1805 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1806 * The aim is to keep the two alignments 'lined up' on their centre columns.
1809 * holds mapped region(s) of this alignment that we are scrolling
1810 * 'to'; may be modified for sequence offset by this method
1811 * @param verticalOffset
1812 * the number of visible sequences to show above the mapped region
1814 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1817 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1818 * mapped), we can make the scroll-to location a sequence above the one
1821 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1822 List<SequenceI> seqs = av.getAlignment().getSequences();
1825 * This is like AlignmentI.findIndex(seq) but here we are matching the
1826 * dataset sequence not the aligned sequence
1828 boolean matched = false;
1829 for (SequenceI seq : seqs)
1831 if (mappedTo == seq.getDatasetSequence())
1839 return; // failsafe, shouldn't happen
1843 * Scroll to position but centring the target residue.
1845 scrollToPosition(sr, verticalOffset, true, true);
1849 * Set a flag to say do not scroll any (cDNA/protein) complement.
1853 protected void setToScrollComplementPanel(boolean b)
1855 this.scrollComplementaryPanel = b;
1859 * Get whether to scroll complement panel
1861 * @return true if cDNA/protein complement panels should be scrolled
1863 protected boolean isSetToScrollComplementPanel()
1865 return this.scrollComplementaryPanel;
1871 * @adjustHeight if true, try to recalculate panel height for visible
1874 protected void refresh(boolean adjustHeight)
1876 validateAnnotationDimensions(adjustHeight);
1880 // sort, repaint, update overview
1881 paintAlignment(true, false);
1885 // lightweight repaint
1892 * Property change event fired when a change is made to the viewport ranges
1893 * object associated with this alignment panel's viewport
1895 public void propertyChange(PropertyChangeEvent evt)
1897 // update this panel's scroll values based on the new viewport ranges values
1898 ViewportRanges ranges = av.getRanges();
1899 int x = ranges.getStartRes();
1900 int y = ranges.getStartSeq();
1901 setScrollValues(x, y);
1903 // now update any complementary alignment (its viewport ranges object
1904 // is different so does not get automatically updated)
1905 if (isSetToScrollComplementPanel())
1907 setToScrollComplementPanel(false);
1908 av.scrollComplementaryAlignment();
1909 setToScrollComplementPanel(true);
1914 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1915 * reference should be nulled when the dialog is closed.
1917 * @param calculationChooser
1919 public void setCalculationDialog(CalculationChooser calculationChooser)
1921 calculationDialog = calculationChooser;
1925 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1928 public CalculationChooser getCalculationDialog()
1930 return calculationDialog;