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 java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Container;
26 import java.awt.Dimension;
28 import java.awt.FontMetrics;
29 import java.awt.Graphics;
30 import java.awt.Graphics2D;
31 import java.awt.event.AdjustmentEvent;
32 import java.awt.event.AdjustmentListener;
33 import java.awt.event.ComponentAdapter;
34 import java.awt.event.ComponentEvent;
35 import java.awt.print.PageFormat;
36 import java.awt.print.Printable;
37 import java.awt.print.PrinterException;
38 import java.beans.PropertyChangeEvent;
39 import java.beans.PropertyChangeListener;
41 import java.io.FileWriter;
42 import java.io.PrintWriter;
43 import java.util.List;
45 import javax.swing.SwingUtilities;
47 import jalview.analysis.AnnotationSorter;
48 import jalview.api.AlignViewportI;
49 import jalview.api.AlignmentViewPanel;
50 import jalview.bin.Cache;
51 import jalview.bin.Console;
52 import jalview.bin.Jalview;
53 import jalview.datamodel.AlignmentI;
54 import jalview.datamodel.HiddenColumns;
55 import jalview.datamodel.SearchResultsI;
56 import jalview.datamodel.SequenceFeature;
57 import jalview.datamodel.SequenceGroup;
58 import jalview.datamodel.SequenceI;
59 import jalview.gui.ImageExporter.ImageWriterI;
60 import jalview.io.HTMLOutput;
61 import jalview.jbgui.GAlignmentPanel;
62 import jalview.math.AlignmentDimension;
63 import jalview.schemes.ResidueProperties;
64 import jalview.structure.StructureSelectionManager;
65 import jalview.util.Comparison;
66 import jalview.util.ImageMaker;
67 import jalview.util.MessageManager;
68 import jalview.viewmodel.ViewportListenerI;
69 import jalview.viewmodel.ViewportRanges;
70 import jalview.workers.VisibleFeaturesAnnotationTracks;
76 * @version $Revision: 1.161 $
78 @SuppressWarnings("serial")
79 public class AlignmentPanel extends GAlignmentPanel implements
80 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
83 * spare space in pixels between sequence id and alignment panel
85 private static final int ID_WIDTH_PADDING = 4;
87 public AlignViewport av;
89 OverviewPanel overviewPanel;
91 private SeqPanel seqPanel;
93 private IdPanel idPanel;
95 IdwidthAdjuster idwidthAdjuster;
97 public AlignFrame alignFrame;
99 private ScalePanel scalePanel;
101 private AnnotationPanel annotationPanel;
103 private AnnotationLabels alabels;
105 private int hextent = 0;
107 private int vextent = 0;
110 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
111 * false, suppresses invoking the same method recursively.
113 private boolean scrollComplementaryPanel = true;
115 private PropertyChangeListener propertyChangeListener;
117 private CalculationChooser calculationDialog;
119 private VisibleFeaturesAnnotationTracks featureCounter;
122 * Creates a new AlignmentPanel object.
127 public AlignmentPanel(AlignFrame af, final AlignViewport av)
129 // setBackground(Color.white); // BH 2019
132 setSeqPanel(new SeqPanel(av, this));
133 setIdPanel(new IdPanel(av, this));
135 setScalePanel(new ScalePanel(av, this));
136 featureCounter = new VisibleFeaturesAnnotationTracks(av,
137 seqPanel.seqCanvas.fr);
139 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
140 idwidthAdjuster = new IdwidthAdjuster(this);
141 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
143 setAnnotationPanel(new AnnotationPanel(this));
144 setAlabels(new AnnotationLabels(this));
146 annotationScroller.setViewportView(getAnnotationPanel());
147 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
149 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
150 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
152 setScrollValues(0, 0);
154 hscroll.addAdjustmentListener(this);
155 vscroll.addAdjustmentListener(this);
157 addComponentListener(new ComponentAdapter()
160 public void componentResized(ComponentEvent evt)
162 // reset the viewport ranges when the alignment panel is resized
163 // in particular, this initialises the end residue value when Jalview
165 ViewportRanges ranges = av.getRanges();
166 if (av.getWrapAlignment())
168 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
169 getSeqPanel().seqCanvas.getWidth());
170 ranges.setViewportWidth(widthInRes);
174 int widthInRes = getSeqPanel().seqCanvas.getWidth()
176 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
177 / av.getCharHeight();
179 ranges.setViewportWidth(widthInRes);
180 ranges.setViewportHeight(heightInSeq);
186 final AlignmentPanel ap = this;
188 propertyChangeListener = new PropertyChangeListener()
191 public void propertyChange(PropertyChangeEvent evt)
193 if (evt.getPropertyName().equals("alignment"))
195 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
200 av.addPropertyChangeListener(propertyChangeListener);
202 av.getRanges().addPropertyChangeListener(this);
204 adjustAnnotationHeight();
209 public AlignViewportI getAlignViewport()
214 public void alignmentChanged()
216 av.alignmentChanged(this);
218 if (getCalculationDialog() != null)
220 getCalculationDialog().validateCalcTypes();
223 alignFrame.updateEditMenuBar();
225 // no idea if we need to update structure
226 paintAlignment(true, true);
233 public void fontChanged()
235 // set idCanvas bufferedImage to null
236 // to prevent drawing old image
237 FontMetrics fm = getFontMetrics(av.getFont());
239 scalePanelHolder.setPreferredSize(
240 new Dimension(10, av.getCharHeight() + fm.getDescent()));
241 idSpaceFillerPanel1.setPreferredSize(
242 new Dimension(10, av.getCharHeight() + fm.getDescent()));
243 idwidthAdjuster.invalidate();
244 scalePanelHolder.invalidate();
245 // BH 2018 getIdPanel().getIdCanvas().gg = null;
246 getSeqPanel().seqCanvas.img = null;
247 getAnnotationPanel().adjustPanelHeight();
249 Dimension d = calculateIdWidth();
250 getIdPanel().getIdCanvas().setPreferredSize(d);
251 hscrollFillerPanel.setPreferredSize(d);
257 * Calculates the width of the alignment labels based on the displayed names
258 * and any bounds on label width set in preferences. The calculated width is
259 * also set as a property of the viewport.
261 * @return Dimension giving the maximum width of the alignment label panel
262 * that should be used.
264 public Dimension calculateIdWidth()
266 int oldWidth = av.getIdWidth();
268 // calculate sensible default width when no preference is available
270 if (av.getIdWidth() < 0)
272 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
273 int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
274 int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
275 r = calculateIdWidth(maxwidth);
276 av.setIdWidth(r.width);
281 r.width = av.getIdWidth();
286 * fudge: if desired width has changed, update layout
287 * (see also paintComponent - updates layout on a repaint)
289 if (r.width != oldWidth)
291 idPanelHolder.setPreferredSize(r);
298 * Calculate the width of the alignment labels based on the displayed names
299 * and any bounds on label width set in preferences.
302 * -1 or maximum width allowed for IdWidth
303 * @return Dimension giving the maximum width of the alignment label panel
304 * that should be used.
306 protected Dimension calculateIdWidth(int maxwidth)
308 Container c = new Container();
310 FontMetrics fm = c.getFontMetrics(
311 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
313 AlignmentI al = av.getAlignment();
317 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
319 SequenceI s = al.getSequenceAt(i);
320 String id = s.getDisplayId(av.getShowJVSuffix());
321 int stringWidth = fm.stringWidth(id);
322 idWidth = Math.max(idWidth, stringWidth);
326 // Also check annotation label widths
329 if (al.getAlignmentAnnotation() != null)
331 fm = c.getFontMetrics(getAlabels().getFont());
333 while (i < al.getAlignmentAnnotation().length)
335 String label = al.getAlignmentAnnotation()[i].label;
336 int stringWidth = fm.stringWidth(label);
337 idWidth = Math.max(idWidth, stringWidth);
342 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
343 w += ID_WIDTH_PADDING;
345 return new Dimension(w, 12);
349 * Highlight the given results on the alignment
352 public void highlightSearchResults(SearchResultsI results)
354 boolean scrolled = scrollToPosition(results, 0, false);
356 boolean fastPaint = !(scrolled && av.getWrapAlignment());
358 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
362 * Scroll the view to show the position of the highlighted region in results
365 * @param searchResults
368 public boolean scrollToPosition(SearchResultsI searchResults)
370 return scrollToPosition(searchResults, 0, false);
374 * Scrolls the view (if necessary) to show the position of the first
375 * highlighted region in results (if any). Answers true if the view was
376 * scrolled, or false if no matched region was found, or it is already
380 * @param verticalOffset
381 * if greater than zero, allows scrolling to a position below the
382 * first displayed sequence
384 * if true, try to centre the search results horizontally in the view
387 protected boolean scrollToPosition(SearchResultsI results,
388 int verticalOffset, boolean centre)
390 int startv, endv, starts, ends;
391 ViewportRanges ranges = av.getRanges();
393 if (results == null || results.isEmpty() || av == null
394 || av.getAlignment() == null)
398 int seqIndex = av.getAlignment().findIndex(results);
403 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
405 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
414 * To centre results, scroll to positions half the visible width
415 * left/right of the start/end positions
419 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
420 start = Math.max(start - offset, 0);
421 end = end + offset - 1;
427 if (end == seq.getEnd())
432 if (av.hasHiddenColumns())
434 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
435 start = hidden.absoluteToVisibleColumn(start);
436 end = hidden.absoluteToVisibleColumn(end);
439 if (!hidden.isVisible(r[0]))
441 // don't scroll - position isn't visible
448 * allow for offset of target sequence (actually scroll to one above it)
450 seqIndex = Math.max(0, seqIndex - verticalOffset);
451 boolean scrollNeeded = true;
453 if (!av.getWrapAlignment())
455 if ((startv = ranges.getStartRes()) >= start)
458 * Scroll left to make start of search results visible
460 setScrollValues(start, seqIndex);
462 else if ((endv = ranges.getEndRes()) <= end)
465 * Scroll right to make end of search results visible
467 setScrollValues(startv + end - endv, seqIndex);
469 else if ((starts = ranges.getStartSeq()) > seqIndex)
472 * Scroll up to make start of search results visible
474 setScrollValues(ranges.getStartRes(), seqIndex);
476 else if ((ends = ranges.getEndSeq()) <= seqIndex)
479 * Scroll down to make end of search results visible
481 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
484 * Else results are already visible - no need to scroll
486 scrollNeeded = false;
490 scrollNeeded = ranges.scrollToWrappedVisible(start);
493 paintAlignment(false, false);
501 * @return DOCUMENT ME!
503 public OverviewPanel getOverviewPanel()
505 return overviewPanel;
514 public void setOverviewPanel(OverviewPanel op)
522 * Hide or show annotation panel
525 public void setAnnotationVisible(boolean b)
527 if (!av.getWrapAlignment())
529 annotationSpaceFillerHolder.setVisible(b);
530 annotationScroller.setVisible(b);
536 * automatically adjust annotation panel height for new annotation whilst
537 * ensuring the alignment is still visible.
540 public void adjustAnnotationHeight()
542 // TODO: display vertical annotation scrollbar if necessary
543 // this is called after loading new annotation onto alignment
544 if (alignFrame.getHeight() == 0)
546 System.out.println("NEEDS FIXING");
548 validateAnnotationDimensions(true);
550 // TODO: many places call this method and also paintAlignment with various
551 // different settings. this means multiple redraws are triggered...
552 paintAlignment(true, av.needToUpdateStructureViews());
556 * calculate the annotation dimensions and refresh slider values accordingly.
557 * need to do repaints/notifys afterwards.
559 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
561 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
562 // are not changing ancestors, and keyboard action listeners do
563 // not need to be reset. addNotify() is a very expensive operation,
564 // requiring a full re-layout of all parents and children.
565 // Note in JComponent:
566 // This method is called by the toolkit internally and should
567 // not be called directly by programs.
568 // I note that addNotify() is called in several areas of Jalview.
570 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
571 annotationHeight = getAnnotationPanel()
572 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
575 annotationScroller.setPreferredSize(
576 new Dimension(annotationScroller.getWidth(), annotationHeight));
578 Dimension e = idPanel.getSize();
579 alabels.setSize(new Dimension(e.width, annotationHeight));
581 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
582 annotationSpaceFillerHolder.getWidth(), annotationHeight));
583 annotationScroller.validate();
584 annotationScroller.addNotify();
588 * update alignment layout for viewport settings
593 public void updateLayout()
596 setAnnotationVisible(av.isShowAnnotation());
597 boolean wrap = av.getWrapAlignment();
598 ViewportRanges ranges = av.getRanges();
599 ranges.setStartSeq(0);
600 scalePanelHolder.setVisible(!wrap);
601 hscroll.setVisible(!wrap);
602 idwidthAdjuster.setVisible(!wrap);
606 annotationScroller.setVisible(false);
607 annotationSpaceFillerHolder.setVisible(false);
609 else if (av.isShowAnnotation())
611 annotationScroller.setVisible(true);
612 annotationSpaceFillerHolder.setVisible(true);
613 validateAnnotationDimensions(false);
616 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
618 { // may not yet be laid out
621 int widthInRes = getSeqPanel().seqCanvas
622 .getWrappedCanvasWidth(canvasWidth);
623 ranges.setViewportWidth(widthInRes);
627 int widthInRes = (canvasWidth / av.getCharWidth());
628 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
629 / av.getCharHeight());
631 ranges.setViewportWidth(widthInRes);
632 ranges.setViewportHeight(heightInSeq);
636 idSpaceFillerPanel1.setVisible(!wrap);
642 * Adjust row/column scrollers to show a visible position in the alignment.
645 * visible column to scroll to
647 * visible row to scroll to
650 public void setScrollValues(int xpos, int ypos)
655 if (av == null || av.getAlignment() == null)
660 if (av.getWrapAlignment())
662 setScrollingForWrappedPanel(x);
666 int width = av.getAlignment().getVisibleWidth();
667 int height = av.getAlignment().getHeight();
669 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
670 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
677 if (vextent > height)
682 if ((hextent + x) > width)
687 if ((vextent + y) > height)
689 y = height - vextent;
702 // update the scroll values
703 hscroll.setValues(x, hextent, 0, width);
704 vscroll.setValues(y, vextent, 0, height);
709 * Respond to adjustment event when horizontal or vertical scrollbar is
713 * adjustment event encoding whether hscroll or vscroll changed
716 public void adjustmentValueChanged(AdjustmentEvent evt)
718 if (av.getWrapAlignment())
720 adjustScrollingWrapped(evt);
724 ViewportRanges ranges = av.getRanges();
726 if (evt.getSource() == hscroll)
728 int oldX = ranges.getStartRes();
729 int oldwidth = ranges.getViewportWidth();
730 int x = hscroll.getValue();
731 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
733 // if we're scrolling to the position we're already at, stop
734 // this prevents infinite recursion of events when the scroll/viewport
735 // ranges values are the same
736 if ((x == oldX) && (width == oldwidth))
740 ranges.setViewportStartAndWidth(x, width);
742 else if (evt.getSource() == vscroll)
744 int oldY = ranges.getStartSeq();
745 int oldheight = ranges.getViewportHeight();
746 int y = vscroll.getValue();
747 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
749 // if we're scrolling to the position we're already at, stop
750 // this prevents infinite recursion of events when the scroll/viewport
751 // ranges values are the same
752 if ((y == oldY) && (height == oldheight))
756 ranges.setViewportStartAndHeight(y, height);
762 * Responds to a scroll change by setting the start position of the viewport.
767 protected void adjustScrollingWrapped(AdjustmentEvent evt)
769 if (evt.getSource() == hscroll)
771 return; // no horizontal scroll when wrapped
773 final ViewportRanges ranges = av.getRanges();
775 if (evt.getSource() == vscroll)
777 int newY = vscroll.getValue();
780 * if we're scrolling to the position we're already at, stop
781 * this prevents infinite recursion of events when the scroll/viewport
782 * ranges values are the same
784 int oldX = ranges.getStartRes();
785 int oldY = ranges.getWrappedScrollPosition(oldX);
793 * limit page up/down to one width's worth of positions
795 int rowSize = ranges.getViewportWidth();
796 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
797 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
802 // This is only called if file loaded is a jar file that
803 // was wrapped when saved and user has wrap alignment true
804 // as preference setting
805 SwingUtilities.invokeLater(new Runnable()
810 // When updating scrolling to use ViewportChange events, this code
811 // could not be validated and it is not clear if it is now being
812 // called. Log warning here in case it is called and unforeseen
815 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
817 // scroll to start of panel
818 ranges.setStartRes(0);
819 ranges.setStartSeq(0);
827 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
830 public void paintAlignment(boolean updateOverview,
831 boolean updateStructures)
833 featureCounter.updateFeatureAnnotationTracks();
834 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
835 av.isShowAutocalculatedAbove());
836 sorter.sort(getAlignment().getAlignmentAnnotation(),
837 av.getSortAnnotationsBy());
840 if (updateStructures)
842 av.getStructureSelectionManager().sequenceColoursChanged(this);
847 if (overviewPanel != null)
849 overviewPanel.updateOverviewImage();
855 public void paintComponent(Graphics g)
857 invalidate(); // needed so that the id width adjuster works correctly
859 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
860 idPanelHolder.setPreferredSize(d);
861 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
863 validate(); // needed so that the id width adjuster works correctly
866 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
867 * though I still think this call should be elsewhere.
869 ViewportRanges ranges = av.getRanges();
870 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
871 super.paintComponent(g);
875 * Set vertical scroll bar position, and number of increments, for wrapped
878 * @param topLeftColumn
879 * the column position at top left (0..)
881 private void setScrollingForWrappedPanel(int topLeftColumn)
883 ViewportRanges ranges = av.getRanges();
884 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
885 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
888 * a scrollbar's value can be set to at most (maximum-extent)
889 * so we add extent (1) to the maxScroll value
891 vscroll.setUnitIncrement(1);
892 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
905 * @return DOCUMENT ME!
907 * @throws PrinterException
911 public int print(Graphics pg, PageFormat pf, int pi)
912 throws PrinterException
914 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
916 int pwidth = (int) pf.getImageableWidth();
917 int pheight = (int) pf.getImageableHeight();
919 if (av.getWrapAlignment())
921 return printWrappedAlignment(pwidth, pheight, pi, pg);
925 return printUnwrapped(pwidth, pheight, pi, pg, pg);
930 * Draws the alignment image, including sequence ids, sequences, and
931 * annotation labels and annotations if shown, on either one or two Graphics
941 * the graphics context for sequence ids and annotation labels
942 * @param alignmentGraphics
943 * the graphics context for sequences and annotations (may or may not
944 * be the same context as idGraphics)
946 * @throws PrinterException
948 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
949 Graphics idGraphics, Graphics alignmentGraphics)
950 throws PrinterException
952 final int idWidth = getVisibleIdWidth(false);
955 * Get the horizontal offset to where we draw the sequences.
956 * This is idWidth if using a single Graphics context, else zero.
958 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
961 FontMetrics fm = getFontMetrics(av.getFont());
962 final int charHeight = av.getCharHeight();
963 final int scaleHeight = charHeight + fm.getDescent();
965 idGraphics.setColor(Color.white);
966 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
967 idGraphics.setFont(av.getFont());
970 * How many sequences and residues can we fit on a printable page?
972 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
974 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
976 final int alignmentWidth = av.getAlignment().getVisibleWidth();
977 int pagesWide = (alignmentWidth / totalRes) + 1;
979 final int startRes = (pageIndex % pagesWide) * totalRes;
980 final int endRes = Math.min(startRes + totalRes - 1,
983 final int startSeq = (pageIndex / pagesWide) * totalSeq;
984 final int alignmentHeight = av.getAlignment().getHeight();
985 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
987 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
989 if (av.isShowAnnotation())
991 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
994 pagesHigh /= pageHeight;
996 if (pageIndex >= (pagesWide * pagesHigh))
998 return Printable.NO_SUCH_PAGE;
1000 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1003 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1005 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1006 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1007 pageWidth - idWidth, scaleHeight);
1008 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1011 * Draw the sequence ids, offset for scale height,
1012 * then reset to top left (0, 0)
1014 idGraphics.translate(0, scaleHeight);
1015 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1016 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1017 : av.getSelectionGroup().getSequences(null);
1018 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1021 idGraphics.setFont(av.getFont());
1022 idGraphics.translate(0, -scaleHeight);
1025 * draw the sequences, offset for scale height, and id width (if using a
1026 * single graphics context), then reset to (0, scale height)
1028 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1029 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1030 startRes, endRes, startSeq, endSeq - 1);
1031 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1033 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1036 * draw annotation labels; drawComponent() translates by
1037 * getScrollOffset(), so compensate for that first;
1038 * then reset to (0, scale height)
1040 int offset = getAlabels().getScrollOffset();
1041 idGraphics.translate(0, -offset);
1042 idGraphics.translate(0, alignmentDrawnHeight);
1043 getAlabels().drawComponent(idGraphics, idWidth);
1044 idGraphics.translate(0, -alignmentDrawnHeight);
1047 * draw the annotations starting at
1048 * (idOffset, alignmentHeight) from (0, scaleHeight)
1050 alignmentGraphics.translate(alignmentGraphicsOffset,
1051 alignmentDrawnHeight);
1052 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1053 alignmentGraphics, -1, startRes, endRes + 1);
1056 return Printable.PAGE_EXISTS;
1060 * Prints one page of an alignment in wrapped mode. Returns
1061 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1062 * no page could be drawn (page number out of range).
1072 * @throws PrinterException
1074 public int printWrappedAlignment(int pageWidth, int pageHeight,
1075 int pageNumber, Graphics g) throws PrinterException
1077 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1079 int annotationHeight = 0;
1080 if (av.isShowAnnotation())
1082 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1085 int hgap = av.getCharHeight();
1086 if (av.getScaleAboveWrapped())
1088 hgap += av.getCharHeight();
1091 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1094 int idWidth = getVisibleIdWidth(false);
1096 int maxwidth = av.getAlignment().getVisibleWidth();
1098 int resWidth = getSeqPanel().seqCanvas
1099 .getWrappedCanvasWidth(pageWidth - idWidth);
1100 av.getRanges().setViewportStartAndWidth(0, resWidth);
1102 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1104 g.setColor(Color.white);
1105 g.fillRect(0, 0, pageWidth, pageHeight);
1106 g.setFont(av.getFont());
1107 g.setColor(Color.black);
1110 * method: print the whole wrapped alignment, but with a clip region that
1111 * is restricted to the requested page; this supports selective print of
1112 * single pages or ranges, (at the cost of repeated processing in the
1113 * 'normal' case, when all pages are printed)
1115 g.translate(0, -pageNumber * pageHeight);
1117 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1120 * draw sequence ids and annotation labels (if shown)
1122 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1123 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1125 g.translate(idWidth, 0);
1127 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1128 pageWidth - idWidth, totalHeight, 0);
1130 if ((pageNumber * pageHeight) < totalHeight)
1132 return Printable.PAGE_EXISTS;
1136 return Printable.NO_SUCH_PAGE;
1141 * get current sequence ID panel width, or nominal value if panel were to be
1142 * displayed using default settings
1146 public int getVisibleIdWidth()
1148 return getVisibleIdWidth(true);
1152 * get current sequence ID panel width, or nominal value if panel were to be
1153 * displayed using default settings
1156 * indicate if the Id width for onscreen or offscreen display should
1160 protected int getVisibleIdWidth(boolean onscreen)
1162 // see if rendering offscreen - check preferences and calc width accordingly
1163 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1165 return calculateIdWidth(-1).width;
1167 Integer idwidth = onscreen ? null
1168 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1169 if (idwidth != null)
1171 return idwidth.intValue() + ID_WIDTH_PADDING;
1174 int w = getIdPanel().getWidth();
1175 return (w > 0 ? w : calculateIdWidth().width);
1179 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1180 * writes it to the specified file
1185 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1187 final int borderBottomOffset = 5;
1189 AlignmentDimension aDimension = getAlignmentDimension();
1190 // todo use a lambda function in place of callback here?
1191 ImageWriterI writer = new ImageWriterI()
1194 public void exportImage(Graphics graphics) throws Exception
1196 if (av.getWrapAlignment())
1198 printWrappedAlignment(aDimension.getWidth(),
1199 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1203 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1204 graphics, graphics);
1209 String fileTitle = alignFrame.getTitle();
1210 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1212 int imageWidth = aDimension.getWidth();
1213 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1214 String of = MessageManager.getString("label.alignment");
1215 exporter.doExport(file, this, imageWidth, imageHeight, of);
1219 * Calculates and returns a suitable width and height (in pixels) for an
1224 public AlignmentDimension getAlignmentDimension()
1226 int maxwidth = av.getAlignment().getVisibleWidth();
1228 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1229 + getScalePanel().getHeight();
1230 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1232 if (av.getWrapAlignment())
1234 height = getWrappedHeight();
1235 if (Jalview.isHeadlessMode())
1237 // need to obtain default alignment width and then add in any
1238 // additional allowance for id margin
1239 // this duplicates the calculation in getWrappedHeight but adjusts for
1241 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1242 - alignFrame.getInsets().left - alignFrame.getInsets().right
1243 - getVisibleIdWidth() + getVisibleIdWidth(false);
1247 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1251 else if (av.isShowAnnotation())
1253 height += getAnnotationPanel().adjustPanelHeight() + 3;
1255 return new AlignmentDimension(width, height);
1259 public void makePNGImageMap(File imgMapFile, String imageName)
1261 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1262 // ////////////////////////////////////////////
1263 int idWidth = getVisibleIdWidth(false);
1264 FontMetrics fm = getFontMetrics(av.getFont());
1265 int scaleHeight = av.getCharHeight() + fm.getDescent();
1268 // ////////////////////////////////
1269 if (imgMapFile != null)
1273 int sSize = av.getAlignment().getHeight();
1274 int alwidth = av.getAlignment().getWidth();
1275 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1276 out.println(HTMLOutput.getImageMapHTML());
1277 out.println("<img src=\"" + imageName
1278 + "\" border=\"0\" usemap=\"#Map\" >"
1279 + "<map name=\"Map\">");
1281 for (int s = 0; s < sSize; s++)
1283 int sy = s * av.getCharHeight() + scaleHeight;
1285 SequenceI seq = av.getAlignment().getSequenceAt(s);
1286 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1287 for (int column = 0; column < alwidth; column++)
1289 StringBuilder text = new StringBuilder(512);
1290 String triplet = null;
1291 if (av.getAlignment().isNucleotide())
1293 triplet = ResidueProperties.nucleotideName
1294 .get(seq.getCharAt(column) + "");
1298 triplet = ResidueProperties.aa2Triplet
1299 .get(seq.getCharAt(column) + "");
1302 if (triplet == null)
1307 int seqPos = seq.findPosition(column);
1308 int gSize = groups.length;
1309 for (int g = 0; g < gSize; g++)
1311 if (text.length() < 1)
1313 text.append("<area shape=\"rect\" coords=\"")
1314 .append((idWidth + column * av.getCharWidth()))
1315 .append(",").append(sy).append(",")
1317 + (column + 1) * av.getCharWidth()))
1318 .append(",").append((av.getCharHeight() + sy))
1319 .append("\"").append(" onMouseOver=\"toolTip('")
1320 .append(seqPos).append(" ").append(triplet);
1323 if (groups[g].getStartRes() < column
1324 && groups[g].getEndRes() > column)
1326 text.append("<br><em>").append(groups[g].getName())
1331 if (text.length() < 1)
1333 text.append("<area shape=\"rect\" coords=\"")
1334 .append((idWidth + column * av.getCharWidth()))
1335 .append(",").append(sy).append(",")
1336 .append((idWidth + (column + 1) * av.getCharWidth()))
1337 .append(",").append((av.getCharHeight() + sy))
1338 .append("\"").append(" onMouseOver=\"toolTip('")
1339 .append(seqPos).append(" ").append(triplet);
1341 if (!Comparison.isGap(seq.getCharAt(column)))
1343 List<SequenceFeature> features = seq.findFeatures(column,
1345 for (SequenceFeature sf : features)
1347 if (sf.isContactFeature())
1349 text.append("<br>").append(sf.getType()).append(" ")
1350 .append(sf.getBegin()).append(":")
1351 .append(sf.getEnd());
1355 text.append("<br>");
1356 text.append(sf.getType());
1357 String description = sf.getDescription();
1358 if (description != null
1359 && !sf.getType().equals(description))
1361 description = description.replace("\"", """);
1362 text.append(" ").append(description);
1365 String status = sf.getStatus();
1366 if (status != null && !"".equals(status))
1368 text.append(" (").append(status).append(")");
1371 if (text.length() > 1)
1373 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1374 out.println(text.toString());
1379 out.println("</map></body></html>");
1382 } catch (Exception ex)
1384 ex.printStackTrace();
1386 } // /////////END OF IMAGE MAP
1391 * Answers the height of the entire alignment in pixels, assuming it is in
1396 int getWrappedHeight()
1398 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1400 if (System.getProperty("java.awt.headless") != null
1401 && System.getProperty("java.awt.headless").equals("true"))
1403 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1404 - vscroll.getPreferredSize().width
1405 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1408 int chunkWidth = getSeqPanel().seqCanvas
1409 .getWrappedCanvasWidth(seqPanelWidth);
1411 int hgap = av.getCharHeight();
1412 if (av.getScaleAboveWrapped())
1414 hgap += av.getCharHeight();
1417 int annotationHeight = 0;
1418 if (av.isShowAnnotation())
1420 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1421 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1424 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1427 int maxwidth = av.getAlignment().getWidth();
1428 if (av.hasHiddenColumns())
1430 maxwidth = av.getAlignment().getHiddenColumns()
1431 .absoluteToVisibleColumn(maxwidth) - 1;
1434 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1440 * close the panel - deregisters all listeners and nulls any references to
1443 public void closePanel()
1445 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1446 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1447 PaintRefresher.RemoveComponent(this);
1452 * try to ensure references are nulled
1454 if (annotationPanel != null)
1456 annotationPanel.dispose();
1457 annotationPanel = null;
1460 if (featureCounter != null)
1462 featureCounter.tidyUp();
1463 featureCounter = null;
1467 av.removePropertyChangeListener(propertyChangeListener);
1468 propertyChangeListener = null;
1469 StructureSelectionManager ssm = av.getStructureSelectionManager();
1470 ssm.removeStructureViewerListener(getSeqPanel(), null);
1471 ssm.removeSelectionListener(getSeqPanel());
1472 ssm.removeCommandListener(av);
1473 ssm.removeStructureViewerListener(getSeqPanel(), null);
1474 ssm.removeSelectionListener(getSeqPanel());
1480 if (Console.isDebugEnabled())
1482 Console.warn("Closing alignment panel which is already closed.");
1488 * Close any open dialogs that would be orphaned when this one is closed
1490 protected void closeChildFrames()
1492 if (overviewPanel != null)
1494 overviewPanel.dispose();
1495 overviewPanel = null;
1497 if (calculationDialog != null)
1499 calculationDialog.closeFrame();
1500 calculationDialog = null;
1505 * hides or shows dynamic annotation rows based on groups and av state flags
1507 public void updateAnnotation()
1509 updateAnnotation(false, false);
1512 public void updateAnnotation(boolean applyGlobalSettings)
1514 updateAnnotation(applyGlobalSettings, false);
1517 public void updateAnnotation(boolean applyGlobalSettings,
1518 boolean preserveNewGroupSettings)
1520 av.updateGroupAnnotationSettings(applyGlobalSettings,
1521 preserveNewGroupSettings);
1522 adjustAnnotationHeight();
1526 public AlignmentI getAlignment()
1528 return av == null ? null : av.getAlignment();
1532 public String getViewName()
1534 return av.getViewName();
1538 * Make/Unmake this alignment panel the current input focus
1542 public void setSelected(boolean b)
1546 if (alignFrame.getSplitViewContainer() != null)
1549 * bring enclosing SplitFrame to front first if there is one
1551 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1553 alignFrame.setSelected(b);
1554 } catch (Exception ex)
1559 setAlignFrameView();
1563 public void setAlignFrameView()
1565 alignFrame.setDisplayedView(this);
1569 public StructureSelectionManager getStructureSelectionManager()
1571 return av.getStructureSelectionManager();
1575 public void raiseOOMWarning(String string, OutOfMemoryError error)
1577 new OOMWarning(string, error, this);
1581 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1584 return new FeatureRenderer(this);
1588 public jalview.api.FeatureRenderer getFeatureRenderer()
1590 return seqPanel.seqCanvas.getFeatureRenderer();
1593 public void updateFeatureRenderer(
1594 jalview.renderer.seqfeatures.FeatureRenderer fr)
1596 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1599 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1601 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1603 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1607 public ScalePanel getScalePanel()
1612 public void setScalePanel(ScalePanel scalePanel)
1614 this.scalePanel = scalePanel;
1617 public SeqPanel getSeqPanel()
1622 public void setSeqPanel(SeqPanel seqPanel)
1624 this.seqPanel = seqPanel;
1627 public AnnotationPanel getAnnotationPanel()
1629 return annotationPanel;
1632 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1634 this.annotationPanel = annotationPanel;
1637 public AnnotationLabels getAlabels()
1642 public void setAlabels(AnnotationLabels alabels)
1644 this.alabels = alabels;
1647 public IdPanel getIdPanel()
1652 public void setIdPanel(IdPanel idPanel)
1654 this.idPanel = idPanel;
1658 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1659 * The aim is to keep the two alignments 'lined up' on their centre columns.
1662 * holds mapped region(s) of this alignment that we are scrolling
1663 * 'to'; may be modified for sequence offset by this method
1664 * @param verticalOffset
1665 * the number of visible sequences to show above the mapped region
1667 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1669 scrollToPosition(sr, verticalOffset, true);
1673 * Set a flag to say do not scroll any (cDNA/protein) complement.
1677 protected void setToScrollComplementPanel(boolean b)
1679 this.scrollComplementaryPanel = b;
1683 * Get whether to scroll complement panel
1685 * @return true if cDNA/protein complement panels should be scrolled
1687 protected boolean isSetToScrollComplementPanel()
1689 return this.scrollComplementaryPanel;
1695 * @adjustHeight if true, try to recalculate panel height for visible
1698 protected void refresh(boolean adjustHeight)
1700 validateAnnotationDimensions(adjustHeight);
1704 // sort, repaint, update overview
1705 paintAlignment(true, false);
1709 // lightweight repaint
1716 * Property change event fired when a change is made to the viewport ranges
1717 * object associated with this alignment panel's viewport
1719 public void propertyChange(PropertyChangeEvent evt)
1721 // update this panel's scroll values based on the new viewport ranges values
1722 ViewportRanges ranges = av.getRanges();
1723 int x = ranges.getStartRes();
1724 int y = ranges.getStartSeq();
1725 setScrollValues(x, y);
1727 // now update any complementary alignment (its viewport ranges object
1728 // is different so does not get automatically updated)
1729 if (isSetToScrollComplementPanel())
1731 setToScrollComplementPanel(false);
1732 av.scrollComplementaryAlignment();
1733 setToScrollComplementPanel(true);
1738 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1739 * reference should be nulled when the dialog is closed.
1741 * @param calculationChooser
1743 public void setCalculationDialog(CalculationChooser calculationChooser)
1745 calculationDialog = calculationChooser;
1749 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1752 public CalculationChooser getCalculationDialog()
1754 return calculationDialog;