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.bin.Jalview;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.HiddenColumns;
30 import jalview.datamodel.SearchResultsI;
31 import jalview.datamodel.SequenceFeature;
32 import jalview.datamodel.SequenceGroup;
33 import jalview.datamodel.SequenceI;
34 import jalview.gui.ImageExporter.ImageWriterI;
35 import jalview.io.HTMLOutput;
36 import jalview.jbgui.GAlignmentPanel;
37 import jalview.math.AlignmentDimension;
38 import jalview.schemes.ResidueProperties;
39 import jalview.structure.StructureSelectionManager;
40 import jalview.util.Comparison;
41 import jalview.util.ImageMaker;
42 import jalview.util.MessageManager;
43 import jalview.viewmodel.ViewportListenerI;
44 import jalview.viewmodel.ViewportRanges;
46 import java.awt.BorderLayout;
47 import java.awt.Color;
48 import java.awt.Container;
49 import java.awt.Dimension;
51 import java.awt.FontMetrics;
52 import java.awt.Graphics;
53 import java.awt.Graphics2D;
54 import java.awt.event.AdjustmentEvent;
55 import java.awt.event.AdjustmentListener;
56 import java.awt.event.ComponentAdapter;
57 import java.awt.event.ComponentEvent;
58 import java.awt.print.PageFormat;
59 import java.awt.print.Printable;
60 import java.awt.print.PrinterException;
61 import java.beans.PropertyChangeEvent;
62 import java.beans.PropertyChangeListener;
64 import java.io.FileWriter;
65 import java.io.PrintWriter;
66 import java.util.List;
68 import javax.swing.SwingUtilities;
74 * @version $Revision: 1.161 $
76 @SuppressWarnings("serial")
77 public class AlignmentPanel extends GAlignmentPanel implements
78 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
81 * spare space in pixels between sequence id and alignment panel
83 private static final int ID_WIDTH_PADDING = 4;
85 public AlignViewport av;
87 OverviewPanel overviewPanel;
89 private SeqPanel seqPanel;
91 private IdPanel idPanel;
93 IdwidthAdjuster idwidthAdjuster;
95 public AlignFrame alignFrame;
97 private ScalePanel scalePanel;
99 private AnnotationPanel annotationPanel;
101 private AnnotationLabels alabels;
103 private int hextent = 0;
105 private int vextent = 0;
108 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
109 * false, suppresses invoking the same method recursively.
111 private boolean scrollComplementaryPanel = true;
113 private PropertyChangeListener propertyChangeListener;
115 private CalculationChooser calculationDialog;
118 * Creates a new AlignmentPanel object.
123 public AlignmentPanel(AlignFrame af, final AlignViewport av)
125 // setBackground(Color.white); // BH 2019
128 setSeqPanel(new SeqPanel(av, this));
129 setIdPanel(new IdPanel(av, this));
131 setScalePanel(new ScalePanel(av, this));
133 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
134 idwidthAdjuster = new IdwidthAdjuster(this);
135 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
137 setAnnotationPanel(new AnnotationPanel(this));
138 setAlabels(new AnnotationLabels(this));
140 annotationScroller.setViewportView(getAnnotationPanel());
141 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
143 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
144 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
146 setScrollValues(0, 0);
148 hscroll.addAdjustmentListener(this);
149 vscroll.addAdjustmentListener(this);
151 addComponentListener(new ComponentAdapter()
154 public void componentResized(ComponentEvent evt)
156 // reset the viewport ranges when the alignment panel is resized
157 // in particular, this initialises the end residue value when Jalview
159 ViewportRanges ranges = av.getRanges();
160 if (av.getWrapAlignment())
162 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
163 getSeqPanel().seqCanvas.getWidth());
164 ranges.setViewportWidth(widthInRes);
168 int widthInRes = getSeqPanel().seqCanvas.getWidth()
170 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
171 / av.getCharHeight();
173 ranges.setViewportWidth(widthInRes);
174 ranges.setViewportHeight(heightInSeq);
180 final AlignmentPanel ap = this;
181 propertyChangeListener = new PropertyChangeListener()
184 public void propertyChange(PropertyChangeEvent evt)
186 if (evt.getPropertyName().equals("alignment"))
188 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
193 av.addPropertyChangeListener(propertyChangeListener);
195 av.getRanges().addPropertyChangeListener(this);
197 adjustAnnotationHeight();
202 public AlignViewportI getAlignViewport()
207 public void alignmentChanged()
209 av.alignmentChanged(this);
211 if (getCalculationDialog() != null)
213 getCalculationDialog().validateCalcTypes();
216 alignFrame.updateEditMenuBar();
218 // no idea if we need to update structure
219 paintAlignment(true, true);
226 public void fontChanged()
228 // set idCanvas bufferedImage to null
229 // to prevent drawing old image
230 FontMetrics fm = getFontMetrics(av.getFont());
232 scalePanelHolder.setPreferredSize(
233 new Dimension(10, av.getCharHeight() + fm.getDescent()));
234 idSpaceFillerPanel1.setPreferredSize(
235 new Dimension(10, av.getCharHeight() + fm.getDescent()));
236 idwidthAdjuster.invalidate();
237 scalePanelHolder.invalidate();
238 // BH 2018 getIdPanel().getIdCanvas().gg = null;
239 getSeqPanel().seqCanvas.img = null;
240 getAnnotationPanel().adjustPanelHeight();
242 Dimension d = calculateIdWidth();
243 getIdPanel().getIdCanvas().setPreferredSize(d);
244 hscrollFillerPanel.setPreferredSize(d);
250 * Calculates the width of the alignment labels based on the displayed names
251 * and any bounds on label width set in preferences. The calculated width is
252 * also set as a property of the viewport.
254 * @return Dimension giving the maximum width of the alignment label panel
255 * that should be used.
257 public Dimension calculateIdWidth()
259 int oldWidth = av.getIdWidth();
261 // calculate sensible default width when no preference is available
263 if (av.getIdWidth() < 0)
265 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
266 int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
267 int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
268 r = calculateIdWidth(maxwidth);
269 av.setIdWidth(r.width);
274 r.width = av.getIdWidth();
279 * fudge: if desired width has changed, update layout
280 * (see also paintComponent - updates layout on a repaint)
282 if (r.width != oldWidth)
284 idPanelHolder.setPreferredSize(r);
291 * Calculate the width of the alignment labels based on the displayed names
292 * and any bounds on label width set in preferences.
295 * -1 or maximum width allowed for IdWidth
296 * @return Dimension giving the maximum width of the alignment label panel
297 * that should be used.
299 protected Dimension calculateIdWidth(int maxwidth)
301 Container c = new Container();
303 FontMetrics fm = c.getFontMetrics(
304 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
306 AlignmentI al = av.getAlignment();
310 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
312 SequenceI s = al.getSequenceAt(i);
313 String id = s.getDisplayId(av.getShowJVSuffix());
314 int stringWidth = fm.stringWidth(id);
315 idWidth = Math.max(idWidth, stringWidth);
319 // Also check annotation label widths
322 if (al.getAlignmentAnnotation() != null)
324 fm = c.getFontMetrics(getAlabels().getFont());
326 while (i < al.getAlignmentAnnotation().length)
328 String label = al.getAlignmentAnnotation()[i].label;
329 int stringWidth = fm.stringWidth(label);
330 idWidth = Math.max(idWidth, stringWidth);
335 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
336 w += ID_WIDTH_PADDING;
338 return new Dimension(w, 12);
342 * Highlight the given results on the alignment
345 public void highlightSearchResults(SearchResultsI results)
347 boolean scrolled = scrollToPosition(results, 0, false);
349 boolean fastPaint = !(scrolled && av.getWrapAlignment());
351 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
355 * Scroll the view to show the position of the highlighted region in results
358 * @param searchResults
361 public boolean scrollToPosition(SearchResultsI searchResults)
363 return scrollToPosition(searchResults, 0, false);
367 * Scrolls the view (if necessary) to show the position of the first
368 * highlighted region in results (if any). Answers true if the view was
369 * scrolled, or false if no matched region was found, or it is already
373 * @param verticalOffset
374 * if greater than zero, allows scrolling to a position below the
375 * first displayed sequence
377 * if true, try to centre the search results horizontally in the view
380 protected boolean scrollToPosition(SearchResultsI results,
381 int verticalOffset, boolean centre)
383 int startv, endv, starts, ends;
384 ViewportRanges ranges = av.getRanges();
386 if (results == null || results.isEmpty() || av == null
387 || av.getAlignment() == null)
391 int seqIndex = av.getAlignment().findIndex(results);
396 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
398 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
407 * To centre results, scroll to positions half the visible width
408 * left/right of the start/end positions
412 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
413 start = Math.max(start - offset, 0);
414 end = end + offset - 1;
420 if (end == seq.getEnd())
425 if (av.hasHiddenColumns())
427 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
428 start = hidden.absoluteToVisibleColumn(start);
429 end = hidden.absoluteToVisibleColumn(end);
432 if (!hidden.isVisible(r[0]))
434 // don't scroll - position isn't visible
441 * allow for offset of target sequence (actually scroll to one above it)
443 seqIndex = Math.max(0, seqIndex - verticalOffset);
444 boolean scrollNeeded = true;
446 if (!av.getWrapAlignment())
448 if ((startv = ranges.getStartRes()) >= start)
451 * Scroll left to make start of search results visible
453 setScrollValues(start, seqIndex);
455 else if ((endv = ranges.getEndRes()) <= end)
458 * Scroll right to make end of search results visible
460 setScrollValues(startv + end - endv, seqIndex);
462 else if ((starts = ranges.getStartSeq()) > seqIndex)
465 * Scroll up to make start of search results visible
467 setScrollValues(ranges.getStartRes(), seqIndex);
469 else if ((ends = ranges.getEndSeq()) <= seqIndex)
472 * Scroll down to make end of search results visible
474 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
478 * Else results are already visible - no need to scroll
480 scrollNeeded = false;
484 scrollNeeded = ranges.scrollToWrappedVisible(start);
487 paintAlignment(false, false);
495 * @return DOCUMENT ME!
497 public OverviewPanel getOverviewPanel()
499 return overviewPanel;
508 public void setOverviewPanel(OverviewPanel op)
516 * Hide or show annotation panel
519 public void setAnnotationVisible(boolean b)
521 if (!av.getWrapAlignment())
523 annotationSpaceFillerHolder.setVisible(b);
524 annotationScroller.setVisible(b);
530 * automatically adjust annotation panel height for new annotation whilst
531 * ensuring the alignment is still visible.
534 public void adjustAnnotationHeight()
536 // TODO: display vertical annotation scrollbar if necessary
537 // this is called after loading new annotation onto alignment
538 if (alignFrame.getHeight() == 0)
540 System.out.println("NEEDS FIXING");
542 validateAnnotationDimensions(true);
544 // TODO: many places call this method and also paintAlignment with various
545 // different settings. this means multiple redraws are triggered...
546 paintAlignment(true, av.needToUpdateStructureViews());
550 * calculate the annotation dimensions and refresh slider values accordingly.
551 * need to do repaints/notifys afterwards.
553 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
555 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
556 // are not changing ancestors, and keyboard action listeners do
557 // not need to be reset. addNotify() is a very expensive operation,
558 // requiring a full re-layout of all parents and children.
559 // Note in JComponent:
560 // This method is called by the toolkit internally and should
561 // not be called directly by programs.
562 // I note that addNotify() is called in several areas of Jalview.
564 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
565 annotationHeight = getAnnotationPanel()
566 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
569 annotationScroller.setPreferredSize(
570 new Dimension(annotationScroller.getWidth(), annotationHeight));
572 Dimension e = idPanel.getSize();
573 alabels.setSize(new Dimension(e.width, annotationHeight));
576 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
577 annotationSpaceFillerHolder.getWidth(), annotationHeight));
578 annotationScroller.validate();
579 annotationScroller.addNotify();
583 * update alignment layout for viewport settings
588 public void updateLayout()
591 setAnnotationVisible(av.isShowAnnotation());
592 boolean wrap = av.getWrapAlignment();
593 ViewportRanges ranges = av.getRanges();
594 ranges.setStartSeq(0);
595 scalePanelHolder.setVisible(!wrap);
596 hscroll.setVisible(!wrap);
597 idwidthAdjuster.setVisible(!wrap);
601 annotationScroller.setVisible(false);
602 annotationSpaceFillerHolder.setVisible(false);
604 else if (av.isShowAnnotation())
606 annotationScroller.setVisible(true);
607 annotationSpaceFillerHolder.setVisible(true);
608 validateAnnotationDimensions(false);
611 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
613 { // may not yet be laid out
616 int widthInRes = getSeqPanel().seqCanvas
617 .getWrappedCanvasWidth(canvasWidth);
618 ranges.setViewportWidth(widthInRes);
622 int widthInRes = (canvasWidth / av.getCharWidth());
623 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
624 / av.getCharHeight());
626 ranges.setViewportWidth(widthInRes);
627 ranges.setViewportHeight(heightInSeq);
631 idSpaceFillerPanel1.setVisible(!wrap);
637 * Adjust row/column scrollers to show a visible position in the alignment.
640 * visible column to scroll to
642 * visible row to scroll to
645 public void setScrollValues(int xpos, int ypos)
650 if (av == null || av.getAlignment() == null)
655 if (av.getWrapAlignment())
657 setScrollingForWrappedPanel(x);
661 int width = av.getAlignment().getVisibleWidth();
662 int height = av.getAlignment().getHeight();
664 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
665 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
672 if (vextent > height)
677 if ((hextent + x) > width)
682 if ((vextent + y) > height)
684 y = height - vextent;
697 // update the scroll values
698 hscroll.setValues(x, hextent, 0, width);
699 vscroll.setValues(y, vextent, 0, height);
704 * Respond to adjustment event when horizontal or vertical scrollbar is
708 * adjustment event encoding whether hscroll or vscroll changed
711 public void adjustmentValueChanged(AdjustmentEvent evt)
713 if (av.getWrapAlignment())
715 adjustScrollingWrapped(evt);
719 ViewportRanges ranges = av.getRanges();
721 if (evt.getSource() == hscroll)
723 int oldX = ranges.getStartRes();
724 int oldwidth = ranges.getViewportWidth();
725 int x = hscroll.getValue();
726 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
728 // if we're scrolling to the position we're already at, stop
729 // this prevents infinite recursion of events when the scroll/viewport
730 // ranges values are the same
731 if ((x == oldX) && (width == oldwidth))
735 ranges.setViewportStartAndWidth(x, width);
737 else if (evt.getSource() == vscroll)
739 int oldY = ranges.getStartSeq();
740 int oldheight = ranges.getViewportHeight();
741 int y = vscroll.getValue();
742 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
744 // if we're scrolling to the position we're already at, stop
745 // this prevents infinite recursion of events when the scroll/viewport
746 // ranges values are the same
747 if ((y == oldY) && (height == oldheight))
751 ranges.setViewportStartAndHeight(y, height);
757 * Responds to a scroll change by setting the start position of the viewport.
762 protected void adjustScrollingWrapped(AdjustmentEvent evt)
764 if (evt.getSource() == hscroll)
766 return; // no horizontal scroll when wrapped
768 final ViewportRanges ranges = av.getRanges();
770 if (evt.getSource() == vscroll)
772 int newY = vscroll.getValue();
775 * if we're scrolling to the position we're already at, stop
776 * this prevents infinite recursion of events when the scroll/viewport
777 * ranges values are the same
779 int oldX = ranges.getStartRes();
780 int oldY = ranges.getWrappedScrollPosition(oldX);
788 * limit page up/down to one width's worth of positions
790 int rowSize = ranges.getViewportWidth();
791 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
792 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
797 // This is only called if file loaded is a jar file that
798 // was wrapped when saved and user has wrap alignment true
799 // as preference setting
800 SwingUtilities.invokeLater(new Runnable()
805 // When updating scrolling to use ViewportChange events, this code
806 // could not be validated and it is not clear if it is now being
807 // called. Log warning here in case it is called and unforeseen
810 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
812 // scroll to start of panel
813 ranges.setStartRes(0);
814 ranges.setStartSeq(0);
822 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
825 public void paintAlignment(boolean updateOverview,
826 boolean updateStructures)
828 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
829 av.isShowAutocalculatedAbove());
830 sorter.sort(getAlignment().getAlignmentAnnotation(),
831 av.getSortAnnotationsBy());
834 if (updateStructures)
836 av.getStructureSelectionManager().sequenceColoursChanged(this);
841 if (overviewPanel != null)
843 overviewPanel.updateOverviewImage();
849 public void paintComponent(Graphics g)
851 invalidate(); // needed so that the id width adjuster works correctly
853 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
854 idPanelHolder.setPreferredSize(d);
855 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
857 validate(); // needed so that the id width adjuster works correctly
860 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
861 * though I still think this call should be elsewhere.
863 ViewportRanges ranges = av.getRanges();
864 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
865 super.paintComponent(g);
869 * Set vertical scroll bar position, and number of increments, for wrapped
872 * @param topLeftColumn
873 * the column position at top left (0..)
875 private void setScrollingForWrappedPanel(int topLeftColumn)
877 ViewportRanges ranges = av.getRanges();
878 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
879 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
882 * a scrollbar's value can be set to at most (maximum-extent)
883 * so we add extent (1) to the maxScroll value
885 vscroll.setUnitIncrement(1);
886 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
899 * @return DOCUMENT ME!
901 * @throws PrinterException
905 public int print(Graphics pg, PageFormat pf, int pi)
906 throws PrinterException
908 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
910 int pwidth = (int) pf.getImageableWidth();
911 int pheight = (int) pf.getImageableHeight();
913 if (av.getWrapAlignment())
915 return printWrappedAlignment(pwidth, pheight, pi, pg);
919 return printUnwrapped(pwidth, pheight, pi, pg, pg);
924 * Draws the alignment image, including sequence ids, sequences, and
925 * annotation labels and annotations if shown, on either one or two Graphics
935 * the graphics context for sequence ids and annotation labels
936 * @param alignmentGraphics
937 * the graphics context for sequences and annotations (may or may not
938 * be the same context as idGraphics)
940 * @throws PrinterException
942 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
943 Graphics idGraphics, Graphics alignmentGraphics)
944 throws PrinterException
946 final int idWidth = getVisibleIdWidth(false);
949 * Get the horizontal offset to where we draw the sequences.
950 * This is idWidth if using a single Graphics context, else zero.
952 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
955 FontMetrics fm = getFontMetrics(av.getFont());
956 final int charHeight = av.getCharHeight();
957 final int scaleHeight = charHeight + fm.getDescent();
959 idGraphics.setColor(Color.white);
960 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
961 idGraphics.setFont(av.getFont());
964 * How many sequences and residues can we fit on a printable page?
966 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
968 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
970 final int alignmentWidth = av.getAlignment().getVisibleWidth();
971 int pagesWide = (alignmentWidth / totalRes) + 1;
973 final int startRes = (pageIndex % pagesWide) * totalRes;
974 final int endRes = Math.min(startRes + totalRes - 1,
977 final int startSeq = (pageIndex / pagesWide) * totalSeq;
978 final int alignmentHeight = av.getAlignment().getHeight();
979 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
981 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
983 if (av.isShowAnnotation())
985 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
988 pagesHigh /= pageHeight;
990 if (pageIndex >= (pagesWide * pagesHigh))
992 return Printable.NO_SUCH_PAGE;
994 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
997 * draw the Scale at horizontal offset, then reset to top left (0, 0)
999 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1000 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1001 pageWidth - idWidth, scaleHeight);
1002 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1005 * Draw the sequence ids, offset for scale height,
1006 * then reset to top left (0, 0)
1008 idGraphics.translate(0, scaleHeight);
1009 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1010 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1011 : av.getSelectionGroup().getSequences(null);
1012 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1015 idGraphics.setFont(av.getFont());
1016 idGraphics.translate(0, -scaleHeight);
1019 * draw the sequences, offset for scale height, and id width (if using a
1020 * single graphics context), then reset to (0, scale height)
1022 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1023 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1024 endRes, startSeq, endSeq - 1);
1025 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1027 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1030 * draw annotation labels; drawComponent() translates by
1031 * getScrollOffset(), so compensate for that first;
1032 * then reset to (0, scale height)
1034 int offset = getAlabels().getScrollOffset();
1035 idGraphics.translate(0, -offset);
1036 idGraphics.translate(0, alignmentDrawnHeight);
1037 getAlabels().drawComponent(idGraphics, idWidth);
1038 idGraphics.translate(0, -alignmentDrawnHeight);
1041 * draw the annotations starting at
1042 * (idOffset, alignmentHeight) from (0, scaleHeight)
1044 alignmentGraphics.translate(alignmentGraphicsOffset,
1045 alignmentDrawnHeight);
1046 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1047 alignmentGraphics, -1, startRes, endRes + 1);
1050 return Printable.PAGE_EXISTS;
1054 * Prints one page of an alignment in wrapped mode. Returns
1055 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1056 * no page could be drawn (page number out of range).
1066 * @throws PrinterException
1068 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1069 Graphics g) throws PrinterException
1071 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1073 int annotationHeight = 0;
1074 if (av.isShowAnnotation())
1076 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1079 int hgap = av.getCharHeight();
1080 if (av.getScaleAboveWrapped())
1082 hgap += av.getCharHeight();
1085 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1088 int idWidth = getVisibleIdWidth(false);
1090 int maxwidth = av.getAlignment().getVisibleWidth();
1092 int resWidth = getSeqPanel().seqCanvas
1093 .getWrappedCanvasWidth(pageWidth - idWidth);
1094 av.getRanges().setViewportStartAndWidth(0, resWidth);
1096 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1098 g.setColor(Color.white);
1099 g.fillRect(0, 0, pageWidth, pageHeight);
1100 g.setFont(av.getFont());
1101 g.setColor(Color.black);
1104 * method: print the whole wrapped alignment, but with a clip region that
1105 * is restricted to the requested page; this supports selective print of
1106 * single pages or ranges, (at the cost of repeated processing in the
1107 * 'normal' case, when all pages are printed)
1109 g.translate(0, -pageNumber * pageHeight);
1111 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1114 * draw sequence ids and annotation labels (if shown)
1116 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1117 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1119 g.translate(idWidth, 0);
1121 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1124 if ((pageNumber * pageHeight) < totalHeight)
1126 return Printable.PAGE_EXISTS;
1130 return Printable.NO_SUCH_PAGE;
1135 * get current sequence ID panel width, or nominal value if panel were to be
1136 * displayed using default settings
1140 public int getVisibleIdWidth()
1142 return getVisibleIdWidth(true);
1146 * get current sequence ID panel width, or nominal value if panel were to be
1147 * displayed using default settings
1150 * indicate if the Id width for onscreen or offscreen display should
1154 protected int getVisibleIdWidth(boolean onscreen)
1156 // see if rendering offscreen - check preferences and calc width accordingly
1157 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1159 return calculateIdWidth(-1).width;
1161 Integer idwidth = onscreen ? null
1162 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1163 if (idwidth != null)
1165 return idwidth.intValue() + ID_WIDTH_PADDING;
1168 int w = getIdPanel().getWidth();
1169 return (w > 0 ? w : calculateIdWidth().width);
1173 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1174 * writes it to the specified file
1179 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1181 final int borderBottomOffset = 5;
1183 AlignmentDimension aDimension = getAlignmentDimension();
1184 // todo use a lambda function in place of callback here?
1185 ImageWriterI writer = new ImageWriterI()
1188 public void exportImage(Graphics graphics) throws Exception
1190 if (av.getWrapAlignment())
1192 printWrappedAlignment(aDimension.getWidth(),
1193 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1197 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1198 graphics, graphics);
1203 String fileTitle = alignFrame.getTitle();
1204 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1206 int imageWidth = aDimension.getWidth();
1207 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1208 String of = MessageManager.getString("label.alignment");
1209 exporter.doExport(file, this, imageWidth, imageHeight, of);
1213 * Calculates and returns a suitable width and height (in pixels) for an
1218 public AlignmentDimension getAlignmentDimension()
1220 int maxwidth = av.getAlignment().getVisibleWidth();
1222 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1223 + getScalePanel().getHeight();
1224 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1226 if (av.getWrapAlignment())
1228 height = getWrappedHeight();
1229 if (Jalview.isHeadlessMode())
1231 // need to obtain default alignment width and then add in any
1232 // additional allowance for id margin
1233 // this duplicates the calculation in getWrappedHeight but adjusts for
1235 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1236 - alignFrame.getInsets().left - alignFrame.getInsets().right
1237 - getVisibleIdWidth() + getVisibleIdWidth(false);
1241 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1245 else if (av.isShowAnnotation())
1247 height += getAnnotationPanel().adjustPanelHeight() + 3;
1249 return new AlignmentDimension(width, height);
1253 public void makePNGImageMap(File imgMapFile, String imageName)
1255 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1256 // ////////////////////////////////////////////
1257 int idWidth = getVisibleIdWidth(false);
1258 FontMetrics fm = getFontMetrics(av.getFont());
1259 int scaleHeight = av.getCharHeight() + fm.getDescent();
1262 // ////////////////////////////////
1263 if (imgMapFile != null)
1267 int sSize = av.getAlignment().getHeight();
1268 int alwidth = av.getAlignment().getWidth();
1269 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1270 out.println(HTMLOutput.getImageMapHTML());
1271 out.println("<img src=\"" + imageName
1272 + "\" border=\"0\" usemap=\"#Map\" >"
1273 + "<map name=\"Map\">");
1275 for (int s = 0; s < sSize; s++)
1277 int sy = s * av.getCharHeight() + scaleHeight;
1279 SequenceI seq = av.getAlignment().getSequenceAt(s);
1280 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1281 for (int column = 0; column < alwidth; column++)
1283 StringBuilder text = new StringBuilder(512);
1284 String triplet = null;
1285 if (av.getAlignment().isNucleotide())
1287 triplet = ResidueProperties.nucleotideName.get(seq
1288 .getCharAt(column) + "");
1292 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1296 if (triplet == null)
1301 int seqPos = seq.findPosition(column);
1302 int gSize = groups.length;
1303 for (int g = 0; g < gSize; g++)
1305 if (text.length() < 1)
1307 text.append("<area shape=\"rect\" coords=\"")
1308 .append((idWidth + column * av.getCharWidth()))
1309 .append(",").append(sy).append(",")
1310 .append((idWidth + (column + 1) * av.getCharWidth()))
1311 .append(",").append((av.getCharHeight() + sy))
1312 .append("\"").append(" onMouseOver=\"toolTip('")
1313 .append(seqPos).append(" ").append(triplet);
1316 if (groups[g].getStartRes() < column
1317 && groups[g].getEndRes() > column)
1319 text.append("<br><em>").append(groups[g].getName())
1324 if (text.length() < 1)
1326 text.append("<area shape=\"rect\" coords=\"")
1327 .append((idWidth + column * av.getCharWidth()))
1328 .append(",").append(sy).append(",")
1329 .append((idWidth + (column + 1) * av.getCharWidth()))
1330 .append(",").append((av.getCharHeight() + sy))
1331 .append("\"").append(" onMouseOver=\"toolTip('")
1332 .append(seqPos).append(" ").append(triplet);
1334 if (!Comparison.isGap(seq.getCharAt(column)))
1336 List<SequenceFeature> features = seq.findFeatures(column, column);
1337 for (SequenceFeature sf : features)
1339 if (sf.isContactFeature())
1341 text.append("<br>").append(sf.getType()).append(" ")
1342 .append(sf.getBegin()).append(":")
1343 .append(sf.getEnd());
1347 text.append("<br>");
1348 text.append(sf.getType());
1349 String description = sf.getDescription();
1350 if (description != null
1351 && !sf.getType().equals(description))
1353 description = description.replace("\"", """);
1354 text.append(" ").append(description);
1357 String status = sf.getStatus();
1358 if (status != null && !"".equals(status))
1360 text.append(" (").append(status).append(")");
1363 if (text.length() > 1)
1365 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1366 out.println(text.toString());
1371 out.println("</map></body></html>");
1374 } catch (Exception ex)
1376 ex.printStackTrace();
1378 } // /////////END OF IMAGE MAP
1383 * Answers the height of the entire alignment in pixels, assuming it is in
1388 int getWrappedHeight()
1390 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1392 if (System.getProperty("java.awt.headless") != null
1393 && System.getProperty("java.awt.headless").equals("true"))
1395 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1396 - vscroll.getPreferredSize().width
1397 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1400 int chunkWidth = getSeqPanel().seqCanvas
1401 .getWrappedCanvasWidth(seqPanelWidth);
1403 int hgap = av.getCharHeight();
1404 if (av.getScaleAboveWrapped())
1406 hgap += av.getCharHeight();
1409 int annotationHeight = 0;
1410 if (av.isShowAnnotation())
1412 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1413 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1416 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1419 int maxwidth = av.getAlignment().getWidth();
1420 if (av.hasHiddenColumns())
1422 maxwidth = av.getAlignment().getHiddenColumns()
1423 .absoluteToVisibleColumn(maxwidth) - 1;
1426 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1432 * close the panel - deregisters all listeners and nulls any references to
1435 public void closePanel()
1437 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1438 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1439 PaintRefresher.RemoveComponent(this);
1444 * try to ensure references are nulled
1446 if (annotationPanel != null)
1448 annotationPanel.dispose();
1449 annotationPanel = null;
1454 av.removePropertyChangeListener(propertyChangeListener);
1455 propertyChangeListener = null;
1456 StructureSelectionManager ssm = av.getStructureSelectionManager();
1457 ssm.removeStructureViewerListener(getSeqPanel(), null);
1458 ssm.removeSelectionListener(getSeqPanel());
1459 ssm.removeCommandListener(av);
1460 ssm.removeStructureViewerListener(getSeqPanel(), null);
1461 ssm.removeSelectionListener(getSeqPanel());
1467 if (Cache.log.isDebugEnabled())
1469 Cache.log.warn("Closing alignment panel which is already closed.");
1475 * Close any open dialogs that would be orphaned when this one is closed
1477 protected void closeChildFrames()
1479 if (overviewPanel != null)
1481 overviewPanel.dispose();
1482 overviewPanel = null;
1484 if (calculationDialog != null)
1486 calculationDialog.closeFrame();
1487 calculationDialog = null;
1492 * hides or shows dynamic annotation rows based on groups and av state flags
1494 public void updateAnnotation()
1496 updateAnnotation(false, false);
1499 public void updateAnnotation(boolean applyGlobalSettings)
1501 updateAnnotation(applyGlobalSettings, false);
1504 public void updateAnnotation(boolean applyGlobalSettings,
1505 boolean preserveNewGroupSettings)
1507 av.updateGroupAnnotationSettings(applyGlobalSettings,
1508 preserveNewGroupSettings);
1509 adjustAnnotationHeight();
1513 public AlignmentI getAlignment()
1515 return av == null ? null : av.getAlignment();
1519 public String getViewName()
1521 return av.getViewName();
1525 * Make/Unmake this alignment panel the current input focus
1529 public void setSelected(boolean b)
1533 if (alignFrame.getSplitViewContainer() != null)
1536 * bring enclosing SplitFrame to front first if there is one
1538 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1540 alignFrame.setSelected(b);
1541 } catch (Exception ex)
1547 alignFrame.setDisplayedView(this);
1552 public StructureSelectionManager getStructureSelectionManager()
1554 return av.getStructureSelectionManager();
1558 public void raiseOOMWarning(String string, OutOfMemoryError error)
1560 new OOMWarning(string, error, this);
1564 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1567 return new FeatureRenderer(this);
1571 public jalview.api.FeatureRenderer getFeatureRenderer()
1573 return seqPanel.seqCanvas.getFeatureRenderer();
1576 public void updateFeatureRenderer(
1577 jalview.renderer.seqfeatures.FeatureRenderer fr)
1579 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1582 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1584 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1586 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1590 public ScalePanel getScalePanel()
1595 public void setScalePanel(ScalePanel scalePanel)
1597 this.scalePanel = scalePanel;
1600 public SeqPanel getSeqPanel()
1605 public void setSeqPanel(SeqPanel seqPanel)
1607 this.seqPanel = seqPanel;
1610 public AnnotationPanel getAnnotationPanel()
1612 return annotationPanel;
1615 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1617 this.annotationPanel = annotationPanel;
1620 public AnnotationLabels getAlabels()
1625 public void setAlabels(AnnotationLabels alabels)
1627 this.alabels = alabels;
1630 public IdPanel getIdPanel()
1635 public void setIdPanel(IdPanel idPanel)
1637 this.idPanel = idPanel;
1641 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1642 * The aim is to keep the two alignments 'lined up' on their centre columns.
1645 * holds mapped region(s) of this alignment that we are scrolling
1646 * 'to'; may be modified for sequence offset by this method
1647 * @param verticalOffset
1648 * the number of visible sequences to show above the mapped region
1650 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1652 scrollToPosition(sr, verticalOffset, true);
1656 * Set a flag to say do not scroll any (cDNA/protein) complement.
1660 protected void setToScrollComplementPanel(boolean b)
1662 this.scrollComplementaryPanel = b;
1666 * Get whether to scroll complement panel
1668 * @return true if cDNA/protein complement panels should be scrolled
1670 protected boolean isSetToScrollComplementPanel()
1672 return this.scrollComplementaryPanel;
1678 * @adjustHeight if true, try to recalculate panel height for visible
1681 protected void refresh(boolean adjustHeight)
1683 validateAnnotationDimensions(adjustHeight);
1687 // sort, repaint, update overview
1688 paintAlignment(true, false);
1692 // lightweight repaint
1699 * Property change event fired when a change is made to the viewport ranges
1700 * object associated with this alignment panel's viewport
1702 public void propertyChange(PropertyChangeEvent evt)
1704 // update this panel's scroll values based on the new viewport ranges values
1705 ViewportRanges ranges = av.getRanges();
1706 int x = ranges.getStartRes();
1707 int y = ranges.getStartSeq();
1708 setScrollValues(x, y);
1710 // now update any complementary alignment (its viewport ranges object
1711 // is different so does not get automatically updated)
1712 if (isSetToScrollComplementPanel())
1714 setToScrollComplementPanel(false);
1715 av.scrollComplementaryAlignment();
1716 setToScrollComplementPanel(true);
1721 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1722 * reference should be nulled when the dialog is closed.
1724 * @param calculationChooser
1726 public void setCalculationDialog(CalculationChooser calculationChooser)
1728 calculationDialog = calculationChooser;
1732 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1735 public CalculationChooser getCalculationDialog()
1737 return calculationDialog;