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.BoundedRangeModel;
46 import javax.swing.SwingUtilities;
48 import jalview.analysis.AnnotationSorter;
49 import jalview.api.AlignViewportI;
50 import jalview.api.AlignmentViewPanel;
51 import jalview.bin.Cache;
52 import jalview.bin.Console;
53 import jalview.bin.Jalview;
54 import jalview.datamodel.AlignmentAnnotation;
55 import jalview.datamodel.AlignmentI;
56 import jalview.datamodel.HiddenColumns;
57 import jalview.datamodel.SearchResultsI;
58 import jalview.datamodel.SequenceFeature;
59 import jalview.datamodel.SequenceGroup;
60 import jalview.datamodel.SequenceI;
61 import jalview.gui.ImageExporter.ImageWriterI;
62 import jalview.io.HTMLOutput;
63 import jalview.io.exceptions.ImageOutputException;
64 import jalview.jbgui.GAlignmentPanel;
65 import jalview.math.AlignmentDimension;
66 import jalview.schemes.ResidueProperties;
67 import jalview.structure.StructureSelectionManager;
68 import jalview.util.Comparison;
69 import jalview.util.ImageMaker;
70 import jalview.util.MessageManager;
71 import jalview.util.imagemaker.BitmapImageSizing;
72 import jalview.viewmodel.ViewportListenerI;
73 import jalview.viewmodel.ViewportRanges;
79 * @version $Revision: 1.161 $
81 @SuppressWarnings("serial")
82 public class AlignmentPanel extends GAlignmentPanel implements
83 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
86 * spare space in pixels between sequence id and alignment panel
88 private static final int ID_WIDTH_PADDING = 4;
90 public AlignViewport av;
92 OverviewPanel overviewPanel;
94 private SeqPanel seqPanel;
96 private IdPanel idPanel;
98 IdwidthAdjuster idwidthAdjuster;
100 public AlignFrame alignFrame;
102 private ScalePanel scalePanel;
104 private AnnotationPanel annotationPanel;
106 private AnnotationLabels alabels;
108 private int hextent = 0;
110 private int vextent = 0;
113 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
114 * false, suppresses invoking the same method recursively.
116 private boolean scrollComplementaryPanel = true;
118 private PropertyChangeListener propertyChangeListener;
120 private CalculationChooser calculationDialog;
123 * Creates a new AlignmentPanel object.
128 public AlignmentPanel(AlignFrame af, final AlignViewport av)
130 // setBackground(Color.white); // BH 2019
133 setSeqPanel(new SeqPanel(av, this));
134 setIdPanel(new IdPanel(av, this));
136 setScalePanel(new ScalePanel(av, this));
138 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
139 idwidthAdjuster = new IdwidthAdjuster(this);
140 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
142 setAnnotationPanel(new AnnotationPanel(this));
143 setAlabels(new AnnotationLabels(this));
145 annotationScroller.setViewportView(getAnnotationPanel());
146 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
148 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
149 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
151 setScrollValues(0, 0);
153 hscroll.addAdjustmentListener(this);
154 vscroll.addAdjustmentListener(this);
156 addComponentListener(new ComponentAdapter()
159 public void componentResized(ComponentEvent evt)
161 // reset the viewport ranges when the alignment panel is resized
162 // in particular, this initialises the end residue value when Jalview
164 ViewportRanges ranges = av.getRanges();
165 if (av.getWrapAlignment())
167 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
168 getSeqPanel().seqCanvas.getWidth());
169 ranges.setViewportWidth(widthInRes);
173 int widthInRes = getSeqPanel().seqCanvas.getWidth()
175 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
176 / av.getCharHeight();
178 ranges.setViewportWidth(widthInRes);
179 ranges.setViewportHeight(heightInSeq);
185 final AlignmentPanel ap = this;
186 propertyChangeListener = new PropertyChangeListener()
189 public void propertyChange(PropertyChangeEvent evt)
191 if (evt.getPropertyName().equals("alignment"))
193 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
198 av.addPropertyChangeListener(propertyChangeListener);
200 av.getRanges().addPropertyChangeListener(this);
202 adjustAnnotationHeight();
207 public AlignViewportI getAlignViewport()
212 public void alignmentChanged()
214 av.alignmentChanged(this);
216 if (getCalculationDialog() != null)
218 getCalculationDialog().validateCalcTypes();
221 alignFrame.updateEditMenuBar();
223 // no idea if we need to update structure
224 paintAlignment(true, true);
231 public void fontChanged()
233 // set idCanvas bufferedImage to null
234 // to prevent drawing old image
235 FontMetrics fm = getFontMetrics(av.getFont());
237 // update the flag controlling whether the grid is too small to render the
239 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
241 scalePanelHolder.setPreferredSize(
242 new Dimension(10, av.getCharHeight() + fm.getDescent()));
243 idSpaceFillerPanel1.setPreferredSize(
244 new Dimension(10, av.getCharHeight() + fm.getDescent()));
245 idwidthAdjuster.invalidate();
246 scalePanelHolder.invalidate();
247 // BH 2018 getIdPanel().getIdCanvas().gg = null;
248 getSeqPanel().seqCanvas.img = null;
249 getAnnotationPanel().adjustPanelHeight();
251 Dimension d = calculateIdWidth();
252 getIdPanel().getIdCanvas().setPreferredSize(d);
253 hscrollFillerPanel.setPreferredSize(d);
259 * Calculates the width of the alignment labels based on the displayed names
260 * and any bounds on label width set in preferences.
262 * The calculated width is set as a property of the viewport and the layout is
265 * @return Dimension giving the maximum width of the alignment label panel
266 * that should be used.
268 public Dimension calculateIdWidth()
270 int oldWidth = av.getIdWidth();
272 // calculate sensible default width when no preference is available
274 if (av.getIdWidth() < 0)
276 r = calculateDefaultAlignmentIdWidth();
277 av.setIdWidth(r.width);
282 r.width = av.getIdWidth();
287 * fudge: if desired width has changed, update layout
288 * (see also paintComponent - updates layout on a repaint)
290 if (r.width != oldWidth)
292 idPanelHolder.setPreferredSize(r);
298 public Dimension calculateDefaultAlignmentIdWidth()
300 return calculateIdWidth(-1, false, false);
304 * pre 2.11.3 Id width calculation - used when importing old projects only
308 public int getLegacyIdWidth()
310 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
311 int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
312 int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
313 Dimension w = calculateIdWidthOrLegacy(true, maxwidth, false, false);
318 * Calculate the width of the alignment labels based on the displayed names
319 * and any bounds on label width set in preferences. Also includes annotations
320 * not actually visible.
322 * FIXME JAL-244 JAL-4091 - doesn't include sequence associated annotation
323 * label decorators and only called during tests
326 * -1 or maximum width allowed for IdWidth
327 * @return Dimension giving the maximum width of the alignment label panel
328 * that should be used.
330 protected Dimension calculateIdWidth(int maxwidth)
332 return calculateIdWidth(maxwidth, true, false);
336 * Calculate the width of the alignment labels based on the displayed names
337 * and any bounds on label width set in preferences.
340 * -1 or maximum width allowed for IdWidth
341 * @param includeAnnotations
342 * - when true includes width of any additional marks in annotation
345 * - when true, ignore label widths for hidden annotation rows
346 * @return Dimension giving the maximum width of the alignment label panel
347 * that should be used.
349 public Dimension calculateIdWidth(int maxwidth,
350 boolean includeAnnotations, boolean visibleOnly)
352 return calculateIdWidthOrLegacy(false, maxwidth, includeAnnotations,
357 * legacy mode or post 2.11.3 ID width calculation
360 * - uses annotation labels, not rendered label width (excludes
361 * additional decorators)
363 * @param includeAnnotations
367 private Dimension calculateIdWidthOrLegacy(boolean legacy, int maxwidth,
368 boolean includeAnnotations, boolean visibleOnly)
370 Container c = new Container();
372 FontMetrics fm = c.getFontMetrics(
373 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
375 AlignmentI al = av.getAlignment();
379 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
381 SequenceI s = al.getSequenceAt(i);
382 String id = s.getDisplayId(av.getShowJVSuffix());
383 int stringWidth = fm.stringWidth(id);
384 idWidth = Math.max(idWidth, stringWidth);
388 // Also check annotation label widths
389 if (includeAnnotations && al.getAlignmentAnnotation() != null)
391 fm = c.getFontMetrics(getAlabels().getFont());
393 if (!legacy || Jalview.isHeadlessMode())
395 AnnotationLabels aal = getAlabels();
396 int stringWidth = aal.drawLabels(null, false, idWidth, false, false,
398 idWidth = Math.max(idWidth, stringWidth);
402 for (i = 0; i < al.getAlignmentAnnotation().length; i++)
404 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
405 if (visibleOnly && !aa.visible)
409 String label = aa.label;
410 int stringWidth = fm.stringWidth(label);
411 idWidth = Math.max(idWidth, stringWidth);
416 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
417 w += ID_WIDTH_PADDING;
419 return new Dimension(w, 12);
423 * Highlight the given results on the alignment
426 public void highlightSearchResults(SearchResultsI results)
428 boolean scrolled = scrollToPosition(results, 0, false);
430 boolean fastPaint = !(scrolled && av.getWrapAlignment());
432 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
436 * Scroll the view to show the position of the highlighted region in results
439 * @param searchResults
442 public boolean scrollToPosition(SearchResultsI searchResults)
444 return scrollToPosition(searchResults, 0, false);
448 * Scrolls the view (if necessary) to show the position of the first
449 * highlighted region in results (if any). Answers true if the view was
450 * scrolled, or false if no matched region was found, or it is already
454 * @param verticalOffset
455 * if greater than zero, allows scrolling to a position below the
456 * first displayed sequence
458 * if true, try to centre the search results horizontally in the view
461 protected boolean scrollToPosition(SearchResultsI results,
462 int verticalOffset, boolean centre)
464 int startv, endv, starts, ends;
465 ViewportRanges ranges = av.getRanges();
467 if (results == null || results.isEmpty() || av == null
468 || av.getAlignment() == null)
472 int seqIndex = av.getAlignment().findIndex(results);
477 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
479 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
488 * To centre results, scroll to positions half the visible width
489 * left/right of the start/end positions
493 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
494 start = Math.max(start - offset, 0);
495 end = end + offset - 1;
501 if (end == seq.getEnd())
506 if (av.hasHiddenColumns())
508 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
509 start = hidden.absoluteToVisibleColumn(start);
510 end = hidden.absoluteToVisibleColumn(end);
513 if (!hidden.isVisible(r[0]))
515 // don't scroll - position isn't visible
522 * allow for offset of target sequence (actually scroll to one above it)
524 seqIndex = Math.max(0, seqIndex - verticalOffset);
525 boolean scrollNeeded = true;
527 if (!av.getWrapAlignment())
529 if ((startv = ranges.getStartRes()) >= start)
532 * Scroll left to make start of search results visible
534 setScrollValues(start, seqIndex);
536 else if ((endv = ranges.getEndRes()) <= end)
539 * Scroll right to make end of search results visible
541 setScrollValues(startv + end - endv, seqIndex);
543 else if ((starts = ranges.getStartSeq()) > seqIndex)
546 * Scroll up to make start of search results visible
548 setScrollValues(ranges.getStartRes(), seqIndex);
550 else if ((ends = ranges.getEndSeq()) <= seqIndex)
553 * Scroll down to make end of search results visible
555 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
558 * Else results are already visible - no need to scroll
560 scrollNeeded = false;
564 scrollNeeded = ranges.scrollToWrappedVisible(start);
567 paintAlignment(false, false);
575 * @return DOCUMENT ME!
577 public OverviewPanel getOverviewPanel()
579 return overviewPanel;
588 public void setOverviewPanel(OverviewPanel op)
596 * Hide or show annotation panel
599 public void setAnnotationVisible(boolean b)
601 if (!av.getWrapAlignment())
603 annotationSpaceFillerHolder.setVisible(b);
604 annotationScroller.setVisible(b);
610 * automatically adjust annotation panel height for new annotation whilst
611 * ensuring the alignment is still visible.
614 public void adjustAnnotationHeight()
616 // TODO: display vertical annotation scrollbar if necessary
617 // this is called after loading new annotation onto alignment
618 if (alignFrame.getHeight() == 0)
620 jalview.bin.Console.error(
621 "adjustAnnotationHeight called with zero height alignment window");
623 validateAnnotationDimensions(true);
625 // TODO: many places call this method and also paintAlignment with various
626 // different settings. this means multiple redraws are triggered...
627 paintAlignment(true, av.needToUpdateStructureViews());
631 * calculate the annotation dimensions and refresh slider values accordingly.
632 * need to do repaints/notifys afterwards.
634 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
636 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
637 // are not changing ancestors, and keyboard action listeners do
638 // not need to be reset. addNotify() is a very expensive operation,
639 // requiring a full re-layout of all parents and children.
640 // Note in JComponent:
641 // This method is called by the toolkit internally and should
642 // not be called directly by programs.
643 // I note that addNotify() is called in several areas of Jalview.
645 AnnotationPanel ap = getAnnotationPanel();
646 int annotationHeight = ap.adjustPanelHeight();
647 annotationHeight = ap.adjustForAlignFrame(adjustPanelHeight,
651 Dimension e = idPanel.getSize();
652 int idWidth = e.width;
653 boolean manuallyAdjusted = this.getIdPanel().getIdCanvas()
654 .isManuallyAdjusted();
655 annotationScroller.setPreferredSize(new Dimension(
656 manuallyAdjusted ? idWidth : annotationScroller.getWidth(),
659 alabels.setPreferredSize(new Dimension(idWidth, annotationHeight));
661 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
662 manuallyAdjusted ? idWidth
663 : annotationSpaceFillerHolder.getWidth(),
665 annotationScroller.validate();
666 annotationScroller.addNotify();
671 * update alignment layout for viewport settings
676 public void updateLayout()
679 setAnnotationVisible(av.isShowAnnotation());
680 boolean wrap = av.getWrapAlignment();
681 ViewportRanges ranges = av.getRanges();
682 ranges.setStartSeq(0);
683 // scalePanelHolder.setVisible(!wrap);
684 hscroll.setVisible(!wrap);
685 // Allow idPanel width adjustment in wrap mode
686 idwidthAdjuster.setVisible(true);
690 annotationScroller.setVisible(false);
691 annotationSpaceFillerHolder.setVisible(false);
693 else if (av.isShowAnnotation())
695 annotationScroller.setVisible(true);
696 annotationSpaceFillerHolder.setVisible(true);
697 validateAnnotationDimensions(false);
700 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
702 { // may not yet be laid out
705 int widthInRes = getSeqPanel().seqCanvas
706 .getWrappedCanvasWidth(canvasWidth);
707 ranges.setViewportWidth(widthInRes);
711 int widthInRes = (canvasWidth / av.getCharWidth());
712 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
713 / av.getCharHeight());
715 ranges.setViewportWidth(widthInRes);
716 ranges.setViewportHeight(heightInSeq);
720 // idSpaceFillerPanel1.setVisible(!wrap);
726 * Adjust row/column scrollers to show a visible position in the alignment.
729 * visible column to scroll to
731 * visible row to scroll to
734 public void setScrollValues(int xpos, int ypos)
739 if (av == null || av.getAlignment() == null)
744 if (av.getWrapAlignment())
746 setScrollingForWrappedPanel(x);
750 int width = av.getAlignment().getVisibleWidth();
751 int height = av.getAlignment().getHeight();
753 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
754 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
761 if (vextent > height)
766 if ((hextent + x) > width)
771 if ((vextent + y) > height)
773 y = height - vextent;
786 // update the scroll values
787 hscroll.setValues(x, hextent, 0, width);
788 vscroll.setValues(y, vextent, 0, height);
793 * Answers true if the panel has no horizontal scrollbar, or the scrollbar is
794 * at its rightmost position, else false.
798 boolean isScrolledFullyRight()
804 BoundedRangeModel model = hscroll.getModel();
805 return (model.getExtent() + model.getValue() >= model.getMaximum());
809 * Respond to adjustment event when horizontal or vertical scrollbar is
813 * adjustment event encoding whether hscroll or vscroll changed
816 public void adjustmentValueChanged(AdjustmentEvent evt)
818 if (av.getWrapAlignment())
820 adjustScrollingWrapped(evt);
824 ViewportRanges ranges = av.getRanges();
826 if (evt.getSource() == hscroll)
828 int oldX = ranges.getStartRes();
829 int oldwidth = ranges.getViewportWidth();
830 int x = hscroll.getValue();
831 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
833 // if we're scrolling to the position we're already at, stop
834 // this prevents infinite recursion of events when the scroll/viewport
835 // ranges values are the same
836 if ((x == oldX) && (width == oldwidth))
840 ranges.setViewportStartAndWidth(x, width);
842 else if (evt.getSource() == vscroll)
844 int oldY = ranges.getStartSeq();
845 int oldheight = ranges.getViewportHeight();
846 int y = vscroll.getValue();
847 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
849 // if we're scrolling to the position we're already at, stop
850 // this prevents infinite recursion of events when the scroll/viewport
851 // ranges values are the same
852 if ((y == oldY) && (height == oldheight))
856 ranges.setViewportStartAndHeight(y, height);
862 * Responds to a scroll change by setting the start position of the viewport.
867 protected void adjustScrollingWrapped(AdjustmentEvent evt)
869 if (evt.getSource() == hscroll)
871 return; // no horizontal scroll when wrapped
873 final ViewportRanges ranges = av.getRanges();
875 if (evt.getSource() == vscroll)
877 int newY = vscroll.getValue();
880 * if we're scrolling to the position we're already at, stop
881 * this prevents infinite recursion of events when the scroll/viewport
882 * ranges values are the same
884 int oldX = ranges.getStartRes();
885 int oldY = ranges.getWrappedScrollPosition(oldX);
893 * limit page up/down to one width's worth of positions
895 int rowSize = ranges.getViewportWidth();
896 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
897 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
902 // This is only called if file loaded is a jar file that
903 // was wrapped when saved and user has wrap alignment true
904 // as preference setting
905 SwingUtilities.invokeLater(new Runnable()
910 // When updating scrolling to use ViewportChange events, this code
911 // could not be validated and it is not clear if it is now being
912 // called. Log warning here in case it is called and unforeseen
915 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
917 // scroll to start of panel
918 ranges.setStartRes(0);
919 ranges.setStartSeq(0);
927 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
930 public void paintAlignment(boolean updateOverview,
931 boolean updateStructures)
933 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
934 av.isShowAutocalculatedAbove());
935 sorter.sort(getAlignment().getAlignmentAnnotation(),
936 av.getSortAnnotationsBy());
939 if (updateStructures)
941 av.getStructureSelectionManager().sequenceColoursChanged(this);
946 if (overviewPanel != null)
948 overviewPanel.updateOverviewImage();
954 public void paintComponent(Graphics g)
956 invalidate(); // needed so that the id width adjuster works correctly
957 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
958 int idWidth = d.width;
960 // check wrapped alignment as at least 1 residue width
961 if (av.getWrapAlignment())
963 SeqCanvas sc = this.getSeqPanel().seqCanvas;
964 if (sc != null && sc.getWidth() < sc.getMinimumWrappedCanvasWidth())
966 // need to make some adjustments
967 idWidth -= (sc.getMinimumWrappedCanvasWidth() - sc.getWidth());
968 av.setIdWidth(idWidth);
969 av.getAlignPanel().getIdPanel().getIdCanvas()
970 .setManuallyAdjusted(true);
972 validateAnnotationDimensions(false);
976 idPanelHolder.setPreferredSize(new Dimension(idWidth, d.height));
977 hscrollFillerPanel.setPreferredSize(new Dimension(idWidth, 12));
979 validate(); // needed so that the id width adjuster works correctly
982 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
983 * though I still think this call should be elsewhere.
985 ViewportRanges ranges = av.getRanges();
986 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
987 super.paintComponent(g);
991 * Set vertical scroll bar position, and number of increments, for wrapped
994 * @param topLeftColumn
995 * the column position at top left (0..)
997 private void setScrollingForWrappedPanel(int topLeftColumn)
999 ViewportRanges ranges = av.getRanges();
1000 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
1001 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
1004 * a scrollbar's value can be set to at most (maximum-extent)
1005 * so we add extent (1) to the maxScroll value
1007 vscroll.setUnitIncrement(1);
1008 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
1021 * @return DOCUMENT ME!
1023 * @throws PrinterException
1027 public int print(Graphics pg, PageFormat pf, int pi)
1028 throws PrinterException
1030 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
1032 int pwidth = (int) pf.getImageableWidth();
1033 int pheight = (int) pf.getImageableHeight();
1035 if (av.getWrapAlignment())
1037 return printWrappedAlignment(pwidth, pheight, pi, pg);
1041 return printUnwrapped(pwidth, pheight, pi, pg, pg);
1046 * Draws the alignment image, including sequence ids, sequences, and
1047 * annotation labels and annotations if shown, on either one or two Graphics
1057 * the graphics context for sequence ids and annotation labels
1058 * @param alignmentGraphics
1059 * the graphics context for sequences and annotations (may or may not
1060 * be the same context as idGraphics)
1062 * @throws PrinterException
1064 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
1065 Graphics idGraphics, Graphics alignmentGraphics)
1066 throws PrinterException
1068 final int idWidth, idWidthForGui;
1069 // otherwise calculate it
1070 idWidth = getVisibleIdWidth(false);
1071 // if (getIdPanel()!=null && getIdPanel().getWidth()>0)
1073 // // use the current IdPanel's width, if its set and non-zero
1074 // idWidthForGui = getIdPanel().getWidth();
1079 * Get the horizontal offset to where we draw the sequences.
1080 * This is idWidth if using a single Graphics context, else zero.
1082 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
1085 FontMetrics fm = getFontMetrics(av.getFont());
1086 final int charHeight = av.getCharHeight();
1087 final int scaleHeight = charHeight + fm.getDescent();
1089 idGraphics.setColor(Color.white);
1090 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1091 idGraphics.setFont(av.getFont());
1094 * How many sequences and residues can we fit on a printable page?
1096 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1098 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1100 final int alignmentWidth = av.getAlignment().getVisibleWidth();
1101 int pagesWide = (alignmentWidth / totalRes) + 1;
1103 final int startRes = (pageIndex % pagesWide) * totalRes;
1104 final int endRes = Math.min(startRes + totalRes - 1,
1105 alignmentWidth - 1);
1107 final int startSeq = (pageIndex / pagesWide) * totalSeq;
1108 final int alignmentHeight = av.getAlignment().getHeight();
1109 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
1111 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1113 if (av.isShowAnnotation())
1115 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1118 pagesHigh /= pageHeight;
1120 if (pageIndex >= (pagesWide * pagesHigh))
1122 return Printable.NO_SUCH_PAGE;
1124 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1126 alignmentGraphics.setColor(Color.white);
1127 alignmentGraphics.fillRect(0, 0, pageWidth, pageHeight + scaleHeight);
1130 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1132 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1133 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1134 pageWidth - idWidth, scaleHeight);
1135 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1138 * Draw the sequence ids, offset for scale height,
1139 * then reset to top left (0, 0)
1141 idGraphics.translate(0, scaleHeight);
1142 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1143 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1144 : av.getSelectionGroup().getSequences(null);
1146 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1147 selection, false, idWidth);
1149 idGraphics.setFont(av.getFont());
1150 idGraphics.translate(0, -scaleHeight);
1153 * draw the sequences, offset for scale height, and id width (if using a
1154 * single graphics context), then reset to (0, scale height)
1156 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1157 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1158 startRes, endRes, startSeq, endSeq - 1);
1159 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1161 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1164 * draw annotation labels; drawComponent() translates by
1165 * getScrollOffset(), so compensate for that first;
1166 * then reset to (0, scale height)
1168 int offset = getAlabels().getScrollOffset();
1169 idGraphics.translate(0, -offset);
1170 idGraphics.translate(0, alignmentDrawnHeight);
1171 getAlabels().drawComponentNotGUI(idGraphics, idWidth);
1172 idGraphics.translate(0, -alignmentDrawnHeight);
1175 * draw the annotations starting at
1176 * (idOffset, alignmentHeight) from (0, scaleHeight)
1178 alignmentGraphics.translate(alignmentGraphicsOffset,
1179 alignmentDrawnHeight);
1181 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1182 alignmentGraphics, -1, startRes, endRes + 1);
1185 return Printable.PAGE_EXISTS;
1189 * Prints one page of an alignment in wrapped mode. Returns
1190 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1191 * no page could be drawn (page number out of range).
1201 * @throws PrinterException
1203 public int printWrappedAlignment(int pageWidth, int pageHeight,
1204 int pageNumber, Graphics g) throws PrinterException
1206 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1208 int annotationHeight = 0;
1209 if (av.isShowAnnotation())
1211 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1214 int hgap = av.getCharHeight();
1215 if (av.getScaleAboveWrapped())
1217 hgap += av.getCharHeight();
1220 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1223 int idWidth = getVisibleIdWidth(false);
1225 int maxwidth = av.getAlignment().getVisibleWidth();
1227 int resWidth = getSeqPanel().seqCanvas
1228 .getWrappedCanvasWidth(pageWidth - idWidth);
1229 av.getRanges().setViewportStartAndWidth(0, resWidth);
1231 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1233 g.setColor(Color.white);
1234 g.fillRect(0, 0, pageWidth, pageHeight);
1235 g.setFont(av.getFont());
1236 g.setColor(Color.black);
1239 * method: print the whole wrapped alignment, but with a clip region that
1240 * is restricted to the requested page; this supports selective print of
1241 * single pages or ranges, (at the cost of repeated processing in the
1242 * 'normal' case, when all pages are printed)
1244 g.translate(0, -pageNumber * pageHeight);
1246 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1249 * draw sequence ids and annotation labels (if shown)
1251 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1252 idCanvas.drawIdsWrappedNoGUI((Graphics2D) g, av, 0, totalHeight);
1254 g.translate(idWidth, 0);
1256 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1257 pageWidth - idWidth, totalHeight, 0);
1259 if ((pageNumber * pageHeight) < totalHeight)
1261 return Printable.PAGE_EXISTS;
1265 return Printable.NO_SUCH_PAGE;
1270 * get current sequence ID panel width, or nominal value if panel were to be
1271 * displayed using default settings
1275 public int getVisibleIdWidth()
1277 return getVisibleIdWidth(true);
1281 * get current sequence ID panel width, or nominal value if panel were to be
1282 * displayed using default settings
1285 * indicate if the Id width for onscreen or offscreen display should
1289 protected int getVisibleIdWidth(boolean onscreen)
1291 // see if rendering offscreen - check preferences and calc width accordingly
1292 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1294 return calculateIdWidth(-1, true, true).width;
1296 Integer idwidth = onscreen ? null
1297 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1298 if (idwidth != null)
1300 return idwidth.intValue() + ID_WIDTH_PADDING;
1303 int w = getIdPanel().getWidth();
1304 w = calculateIdWidth(-1, true, true).width;
1305 return (w > 0 ? w : calculateIdWidth().width);
1308 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer)
1309 throws ImageOutputException
1311 makeAlignmentImage(type, file, renderer,
1312 BitmapImageSizing.defaultBitmapImageSizing());
1316 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1317 * writes it to the specified file
1321 * @param textrenderer
1322 * @param bitmapscale
1324 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer,
1325 BitmapImageSizing userBis) throws ImageOutputException
1327 final int borderBottomOffset = 5;
1329 AlignmentDimension aDimension = getAlignmentDimension();
1331 // todo use a lambda function in place of callback here?
1332 ImageWriterI writer = new ImageWriterI()
1335 public void exportImage(Graphics graphics) throws Exception
1337 if (av.getWrapAlignment())
1339 printWrappedAlignment(aDimension.getWidth(),
1340 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1344 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1345 graphics, graphics);
1350 String fileTitle = alignFrame.getTitle();
1351 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1353 int imageWidth = aDimension.getWidth();
1354 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1355 String of = MessageManager.getString("label.alignment");
1356 exporter.doExport(file, this, imageWidth, imageHeight, of, renderer,
1361 * Calculates and returns a suitable width and height (in pixels) for an
1366 public AlignmentDimension getAlignmentDimension()
1368 int maxwidth = av.getAlignment().getVisibleWidth();
1370 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1371 + getScalePanel().getHeight();
1372 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1374 if (av.getWrapAlignment())
1376 height = getWrappedHeight();
1377 if (Jalview.isHeadlessMode())
1379 // need to obtain default alignment width and then add in any
1380 // additional allowance for id margin
1381 // this duplicates the calculation in getWrappedHeight but adjusts for
1383 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1384 - alignFrame.getInsets().left - alignFrame.getInsets().right
1385 - getVisibleIdWidth() + getVisibleIdWidth(false);
1389 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1393 else if (av.isShowAnnotation())
1395 height += getAnnotationPanel().adjustPanelHeight() + 3;
1397 return new AlignmentDimension(width, height);
1401 public void makePNGImageMap(File imgMapFile, String imageName)
1402 throws ImageOutputException
1404 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1405 // ////////////////////////////////////////////
1406 int idWidth = getVisibleIdWidth(false);
1407 FontMetrics fm = getFontMetrics(av.getFont());
1408 int scaleHeight = av.getCharHeight() + fm.getDescent();
1411 // ////////////////////////////////
1412 if (imgMapFile != null)
1416 int sSize = av.getAlignment().getHeight();
1417 int alwidth = av.getAlignment().getWidth();
1418 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1419 out.println(HTMLOutput.getImageMapHTML());
1420 out.println("<img src=\"" + imageName
1421 + "\" border=\"0\" usemap=\"#Map\" >"
1422 + "<map name=\"Map\">");
1424 for (int s = 0; s < sSize; s++)
1426 int sy = s * av.getCharHeight() + scaleHeight;
1428 SequenceI seq = av.getAlignment().getSequenceAt(s);
1429 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1430 for (int column = 0; column < alwidth; column++)
1432 StringBuilder text = new StringBuilder(512);
1433 String triplet = null;
1434 if (av.getAlignment().isNucleotide())
1436 triplet = ResidueProperties.nucleotideName
1437 .get(seq.getCharAt(column) + "");
1441 triplet = ResidueProperties.aa2Triplet
1442 .get(seq.getCharAt(column) + "");
1445 if (triplet == null)
1450 int seqPos = seq.findPosition(column);
1451 int gSize = groups.length;
1452 for (int g = 0; g < gSize; g++)
1454 if (text.length() < 1)
1456 text.append("<area shape=\"rect\" coords=\"")
1457 .append((idWidth + column * av.getCharWidth()))
1458 .append(",").append(sy).append(",")
1460 + (column + 1) * av.getCharWidth()))
1461 .append(",").append((av.getCharHeight() + sy))
1462 .append("\"").append(" onMouseOver=\"toolTip('")
1463 .append(seqPos).append(" ").append(triplet);
1466 if (groups[g].getStartRes() < column
1467 && groups[g].getEndRes() > column)
1469 text.append("<br><em>").append(groups[g].getName())
1474 if (text.length() < 1)
1476 text.append("<area shape=\"rect\" coords=\"")
1477 .append((idWidth + column * av.getCharWidth()))
1478 .append(",").append(sy).append(",")
1479 .append((idWidth + (column + 1) * av.getCharWidth()))
1480 .append(",").append((av.getCharHeight() + sy))
1481 .append("\"").append(" onMouseOver=\"toolTip('")
1482 .append(seqPos).append(" ").append(triplet);
1484 if (!Comparison.isGap(seq.getCharAt(column)))
1486 List<SequenceFeature> features = seq.findFeatures(column,
1488 for (SequenceFeature sf : features)
1490 if (sf.isContactFeature())
1492 text.append("<br>").append(sf.getType()).append(" ")
1493 .append(sf.getBegin()).append(":")
1494 .append(sf.getEnd());
1498 text.append("<br>");
1499 text.append(sf.getType());
1500 String description = sf.getDescription();
1501 if (description != null
1502 && !sf.getType().equals(description))
1504 description = description.replace("\"", """);
1505 text.append(" ").append(description);
1508 String status = sf.getStatus();
1509 if (status != null && !"".equals(status))
1511 text.append(" (").append(status).append(")");
1514 if (text.length() > 1)
1516 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1517 out.println(text.toString());
1522 out.println("</map></body></html>");
1525 } catch (Exception ex)
1527 throw new ImageOutputException(
1528 "couldn't write ImageMap due to unexpected error", ex);
1530 } // /////////END OF IMAGE MAP
1535 * Answers the height of the entire alignment in pixels, assuming it is in
1540 int getWrappedHeight()
1542 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1544 if (Jalview.isHeadlessMode())
1546 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1547 - vscroll.getPreferredSize().width
1548 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1551 int chunkWidth = getSeqPanel().seqCanvas
1552 .getWrappedCanvasWidth(seqPanelWidth);
1554 int hgap = av.getCharHeight();
1555 if (av.getScaleAboveWrapped())
1557 hgap += av.getCharHeight();
1560 int annotationHeight = 0;
1561 if (av.isShowAnnotation())
1563 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1564 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1567 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1570 int maxwidth = av.getAlignment().getWidth();
1571 if (av.hasHiddenColumns())
1573 maxwidth = av.getAlignment().getHiddenColumns()
1574 .absoluteToVisibleColumn(maxwidth) - 1;
1577 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1583 * close the panel - deregisters all listeners and nulls any references to
1586 public void closePanel()
1588 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1589 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1590 PaintRefresher.RemoveComponent(this);
1595 * try to ensure references are nulled
1597 if (annotationPanel != null)
1599 annotationPanel.dispose();
1600 annotationPanel = null;
1605 av.removePropertyChangeListener(propertyChangeListener);
1606 propertyChangeListener = null;
1607 StructureSelectionManager ssm = av.getStructureSelectionManager();
1608 ssm.removeStructureViewerListener(getSeqPanel(), null);
1609 ssm.removeSelectionListener(getSeqPanel());
1610 ssm.removeCommandListener(av);
1611 ssm.removeStructureViewerListener(getSeqPanel(), null);
1612 ssm.removeSelectionListener(getSeqPanel());
1618 if (Console.isDebugEnabled())
1620 Console.warn("Closing alignment panel which is already closed.");
1626 * Close any open dialogs that would be orphaned when this one is closed
1628 protected void closeChildFrames()
1630 if (overviewPanel != null)
1632 overviewPanel.dispose();
1633 overviewPanel = null;
1635 if (calculationDialog != null)
1637 calculationDialog.closeFrame();
1638 calculationDialog = null;
1643 * hides or shows dynamic annotation rows based on groups and av state flags
1645 public void updateAnnotation()
1647 updateAnnotation(false, false);
1650 public void updateAnnotation(boolean applyGlobalSettings)
1652 updateAnnotation(applyGlobalSettings, false);
1655 public void updateAnnotation(boolean applyGlobalSettings,
1656 boolean preserveNewGroupSettings)
1658 av.updateGroupAnnotationSettings(applyGlobalSettings,
1659 preserveNewGroupSettings);
1660 adjustAnnotationHeight();
1664 public AlignmentI getAlignment()
1666 return av == null ? null : av.getAlignment();
1670 public String getViewName()
1672 return av.getViewName();
1676 * Make/Unmake this alignment panel the current input focus
1680 public void setSelected(boolean b)
1684 if (alignFrame.getSplitViewContainer() != null)
1687 * bring enclosing SplitFrame to front first if there is one
1689 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1691 alignFrame.setSelected(b);
1692 } catch (Exception ex)
1697 setAlignFrameView();
1701 public void setAlignFrameView()
1703 alignFrame.setDisplayedView(this);
1707 public StructureSelectionManager getStructureSelectionManager()
1709 return av.getStructureSelectionManager();
1713 public void raiseOOMWarning(String string, OutOfMemoryError error)
1715 new OOMWarning(string, error, this);
1719 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1722 return new FeatureRenderer(this);
1726 public jalview.api.FeatureRenderer getFeatureRenderer()
1728 return seqPanel.seqCanvas.getFeatureRenderer();
1731 public void updateFeatureRenderer(
1732 jalview.renderer.seqfeatures.FeatureRenderer fr)
1734 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1737 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1739 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1741 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1745 public ScalePanel getScalePanel()
1750 public void setScalePanel(ScalePanel scalePanel)
1752 this.scalePanel = scalePanel;
1755 public SeqPanel getSeqPanel()
1760 public void setSeqPanel(SeqPanel seqPanel)
1762 this.seqPanel = seqPanel;
1765 public AnnotationPanel getAnnotationPanel()
1767 return annotationPanel;
1770 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1772 this.annotationPanel = annotationPanel;
1775 public AnnotationLabels getAlabels()
1780 public void setAlabels(AnnotationLabels alabels)
1782 this.alabels = alabels;
1785 public IdPanel getIdPanel()
1790 public void setIdPanel(IdPanel idPanel)
1792 this.idPanel = idPanel;
1796 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1797 * The aim is to keep the two alignments 'lined up' on their centre columns.
1800 * holds mapped region(s) of this alignment that we are scrolling
1801 * 'to'; may be modified for sequence offset by this method
1802 * @param verticalOffset
1803 * the number of visible sequences to show above the mapped region
1805 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1807 scrollToPosition(sr, verticalOffset, true);
1811 * Set a flag to say do not scroll any (cDNA/protein) complement.
1815 protected void setToScrollComplementPanel(boolean b)
1817 this.scrollComplementaryPanel = b;
1821 * Get whether to scroll complement panel
1823 * @return true if cDNA/protein complement panels should be scrolled
1825 protected boolean isSetToScrollComplementPanel()
1827 return this.scrollComplementaryPanel;
1833 * @adjustHeight if true, try to recalculate panel height for visible
1836 protected void refresh(boolean adjustHeight)
1838 validateAnnotationDimensions(adjustHeight);
1842 // sort, repaint, update overview
1843 paintAlignment(true, false);
1847 // lightweight repaint
1854 * Property change event fired when a change is made to the viewport ranges
1855 * object associated with this alignment panel's viewport
1857 public void propertyChange(PropertyChangeEvent evt)
1859 // update this panel's scroll values based on the new viewport ranges values
1860 ViewportRanges ranges = av.getRanges();
1861 int x = ranges.getStartRes();
1862 int y = ranges.getStartSeq();
1863 setScrollValues(x, y);
1865 // now update any complementary alignment (its viewport ranges object
1866 // is different so does not get automatically updated)
1867 if (isSetToScrollComplementPanel())
1869 setToScrollComplementPanel(false);
1870 av.scrollComplementaryAlignment();
1871 setToScrollComplementPanel(true);
1876 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1877 * reference should be nulled when the dialog is closed.
1879 * @param calculationChooser
1881 public void setCalculationDialog(CalculationChooser calculationChooser)
1883 calculationDialog = calculationChooser;
1887 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1890 public CalculationChooser getCalculationDialog()
1892 return calculationDialog;
1896 * Constructs and sets the title for the Overview window (if there is one),
1897 * including the align frame's title, and view name (if applicable). Returns
1898 * the title, or null if this panel has no Overview window open.
1903 public String setOverviewTitle(AlignFrame alignFrame)
1905 if (this.overviewPanel == null)
1909 String overviewTitle = MessageManager
1910 .formatMessage("label.overview_params", new Object[]
1911 { alignFrame.getTitle() });
1912 String viewName = getViewName();
1913 if (viewName != null)
1915 overviewTitle += (" " + viewName);
1917 overviewPanel.setTitle(overviewTitle);
1918 return overviewTitle;
1922 * If this alignment panel has an Overview panel open, closes it
1924 public void closeOverviewPanel()
1926 if (overviewPanel != null)
1928 overviewPanel.close();
1929 overviewPanel = null;