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)
393 fm = c.getFontMetrics(getAlabels().getFont());
396 if (!legacy || Jalview.isHeadlessMode())
398 AnnotationLabels aal = getAlabels();
399 int stringWidth = aal.drawLabels(null, false, idWidth, false, false,
401 idWidth = Math.max(idWidth, stringWidth);
405 for (i = 0; i < al.getAlignmentAnnotation().length; i++)
407 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
408 if (visibleOnly && !aa.visible)
412 String label = aa.label;
413 int stringWidth = fm.stringWidth(label);
414 idWidth = Math.max(idWidth, stringWidth);
419 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
420 w += ID_WIDTH_PADDING;
422 return new Dimension(w, 12);
426 * Highlight the given results on the alignment
429 public void highlightSearchResults(SearchResultsI results)
431 boolean scrolled = scrollToPosition(results, 0, false);
433 boolean fastPaint = !(scrolled && av.getWrapAlignment());
435 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
439 * Scroll the view to show the position of the highlighted region in results
442 * @param searchResults
445 public boolean scrollToPosition(SearchResultsI searchResults)
447 return scrollToPosition(searchResults, 0, false);
451 * Scrolls the view (if necessary) to show the position of the first
452 * highlighted region in results (if any). Answers true if the view was
453 * scrolled, or false if no matched region was found, or it is already
457 * @param verticalOffset
458 * if greater than zero, allows scrolling to a position below the
459 * first displayed sequence
461 * if true, try to centre the search results horizontally in the view
464 protected boolean scrollToPosition(SearchResultsI results,
465 int verticalOffset, boolean centre)
467 int startv, endv, starts, ends;
468 ViewportRanges ranges = av.getRanges();
470 if (results == null || results.isEmpty() || av == null
471 || av.getAlignment() == null)
475 int seqIndex = av.getAlignment().findIndex(results);
480 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
482 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
491 * To centre results, scroll to positions half the visible width
492 * left/right of the start/end positions
496 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
497 start = Math.max(start - offset, 0);
498 end = end + offset - 1;
504 if (end == seq.getEnd())
509 if (av.hasHiddenColumns())
511 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
512 start = hidden.absoluteToVisibleColumn(start);
513 end = hidden.absoluteToVisibleColumn(end);
516 if (!hidden.isVisible(r[0]))
518 // don't scroll - position isn't visible
525 * allow for offset of target sequence (actually scroll to one above it)
527 seqIndex = Math.max(0, seqIndex - verticalOffset);
528 boolean scrollNeeded = true;
530 if (!av.getWrapAlignment())
532 if ((startv = ranges.getStartRes()) >= start)
535 * Scroll left to make start of search results visible
537 setScrollValues(start, seqIndex);
539 else if ((endv = ranges.getEndRes()) <= end)
542 * Scroll right to make end of search results visible
544 setScrollValues(startv + end - endv, seqIndex);
546 else if ((starts = ranges.getStartSeq()) > seqIndex)
549 * Scroll up to make start of search results visible
551 setScrollValues(ranges.getStartRes(), seqIndex);
553 else if ((ends = ranges.getEndSeq()) <= seqIndex)
556 * Scroll down to make end of search results visible
558 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
561 * Else results are already visible - no need to scroll
563 scrollNeeded = false;
567 scrollNeeded = ranges.scrollToWrappedVisible(start);
570 paintAlignment(false, false);
578 * @return DOCUMENT ME!
580 public OverviewPanel getOverviewPanel()
582 return overviewPanel;
591 public void setOverviewPanel(OverviewPanel op)
599 * Hide or show annotation panel
602 public void setAnnotationVisible(boolean b)
604 if (!av.getWrapAlignment())
606 annotationSpaceFillerHolder.setVisible(b);
607 annotationScroller.setVisible(b);
613 * automatically adjust annotation panel height for new annotation whilst
614 * ensuring the alignment is still visible.
617 public void adjustAnnotationHeight()
619 // TODO: display vertical annotation scrollbar if necessary
620 // this is called after loading new annotation onto alignment
621 if (alignFrame.getHeight() == 0)
623 jalview.bin.Console.error(
624 "adjustAnnotationHeight called with zero height alignment window");
626 validateAnnotationDimensions(true);
628 // TODO: many places call this method and also paintAlignment with various
629 // different settings. this means multiple redraws are triggered...
630 paintAlignment(true, av.needToUpdateStructureViews());
634 * calculate the annotation dimensions and refresh slider values accordingly.
635 * need to do repaints/notifys afterwards.
637 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
639 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
640 // are not changing ancestors, and keyboard action listeners do
641 // not need to be reset. addNotify() is a very expensive operation,
642 // requiring a full re-layout of all parents and children.
643 // Note in JComponent:
644 // This method is called by the toolkit internally and should
645 // not be called directly by programs.
646 // I note that addNotify() is called in several areas of Jalview.
648 AnnotationPanel ap = getAnnotationPanel();
649 int annotationHeight = ap.adjustPanelHeight();
650 annotationHeight = ap.adjustForAlignFrame(adjustPanelHeight,
654 Dimension e = idPanel.getSize();
655 int idWidth = e.width;
656 boolean manuallyAdjusted = this.getIdPanel().getIdCanvas()
657 .isManuallyAdjusted();
658 annotationScroller.setPreferredSize(new Dimension(
659 manuallyAdjusted ? idWidth : annotationScroller.getWidth(),
662 alabels.setPreferredSize(new Dimension(idWidth, annotationHeight));
664 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
665 manuallyAdjusted ? idWidth
666 : annotationSpaceFillerHolder.getWidth(),
668 annotationScroller.validate();
669 annotationScroller.addNotify();
674 * update alignment layout for viewport settings
679 public void updateLayout()
682 setAnnotationVisible(av.isShowAnnotation());
683 boolean wrap = av.getWrapAlignment();
684 ViewportRanges ranges = av.getRanges();
685 ranges.setStartSeq(0);
686 // scalePanelHolder.setVisible(!wrap);
687 hscroll.setVisible(!wrap);
688 // Allow idPanel width adjustment in wrap mode
689 idwidthAdjuster.setVisible(true);
693 annotationScroller.setVisible(false);
694 annotationSpaceFillerHolder.setVisible(false);
696 else if (av.isShowAnnotation())
698 annotationScroller.setVisible(true);
699 annotationSpaceFillerHolder.setVisible(true);
700 validateAnnotationDimensions(false);
703 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
705 { // may not yet be laid out
708 int widthInRes = getSeqPanel().seqCanvas
709 .getWrappedCanvasWidth(canvasWidth);
710 ranges.setViewportWidth(widthInRes);
714 int widthInRes = (canvasWidth / av.getCharWidth());
715 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
716 / av.getCharHeight());
718 ranges.setViewportWidth(widthInRes);
719 ranges.setViewportHeight(heightInSeq);
723 // idSpaceFillerPanel1.setVisible(!wrap);
729 * Adjust row/column scrollers to show a visible position in the alignment.
732 * visible column to scroll to
734 * visible row to scroll to
737 public void setScrollValues(int xpos, int ypos)
742 if (av == null || av.getAlignment() == null)
747 if (av.getWrapAlignment())
749 setScrollingForWrappedPanel(x);
753 int width = av.getAlignment().getVisibleWidth();
754 int height = av.getAlignment().getHeight();
756 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
757 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
764 if (vextent > height)
769 if ((hextent + x) > width)
774 if ((vextent + y) > height)
776 y = height - vextent;
789 // update the scroll values
790 hscroll.setValues(x, hextent, 0, width);
791 vscroll.setValues(y, vextent, 0, height);
796 * Answers true if the panel has no horizontal scrollbar, or the scrollbar is
797 * at its rightmost position, else false.
801 boolean isScrolledFullyRight()
807 BoundedRangeModel model = hscroll.getModel();
808 return (model.getExtent() + model.getValue() >= model.getMaximum());
812 * Respond to adjustment event when horizontal or vertical scrollbar is
816 * adjustment event encoding whether hscroll or vscroll changed
819 public void adjustmentValueChanged(AdjustmentEvent evt)
821 if (av.getWrapAlignment())
823 adjustScrollingWrapped(evt);
827 ViewportRanges ranges = av.getRanges();
829 if (evt.getSource() == hscroll)
831 int oldX = ranges.getStartRes();
832 int oldwidth = ranges.getViewportWidth();
833 int x = hscroll.getValue();
834 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
836 // if we're scrolling to the position we're already at, stop
837 // this prevents infinite recursion of events when the scroll/viewport
838 // ranges values are the same
839 if ((x == oldX) && (width == oldwidth))
843 ranges.setViewportStartAndWidth(x, width);
845 else if (evt.getSource() == vscroll)
847 int oldY = ranges.getStartSeq();
848 int oldheight = ranges.getViewportHeight();
849 int y = vscroll.getValue();
850 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
852 // if we're scrolling to the position we're already at, stop
853 // this prevents infinite recursion of events when the scroll/viewport
854 // ranges values are the same
855 if ((y == oldY) && (height == oldheight))
859 ranges.setViewportStartAndHeight(y, height);
865 * Responds to a scroll change by setting the start position of the viewport.
870 protected void adjustScrollingWrapped(AdjustmentEvent evt)
872 if (evt.getSource() == hscroll)
874 return; // no horizontal scroll when wrapped
876 final ViewportRanges ranges = av.getRanges();
878 if (evt.getSource() == vscroll)
880 int newY = vscroll.getValue();
883 * if we're scrolling to the position we're already at, stop
884 * this prevents infinite recursion of events when the scroll/viewport
885 * ranges values are the same
887 int oldX = ranges.getStartRes();
888 int oldY = ranges.getWrappedScrollPosition(oldX);
896 * limit page up/down to one width's worth of positions
898 int rowSize = ranges.getViewportWidth();
899 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
900 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
905 // This is only called if file loaded is a jar file that
906 // was wrapped when saved and user has wrap alignment true
907 // as preference setting
908 SwingUtilities.invokeLater(new Runnable()
913 // When updating scrolling to use ViewportChange events, this code
914 // could not be validated and it is not clear if it is now being
915 // called. Log warning here in case it is called and unforeseen
918 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
920 // scroll to start of panel
921 ranges.setStartRes(0);
922 ranges.setStartSeq(0);
930 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
933 public void paintAlignment(boolean updateOverview,
934 boolean updateStructures)
936 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
937 av.isShowAutocalculatedAbove());
938 sorter.sort(getAlignment().getAlignmentAnnotation(),
939 av.getSortAnnotationsBy());
942 if (updateStructures)
944 av.getStructureSelectionManager().sequenceColoursChanged(this);
949 if (overviewPanel != null)
951 overviewPanel.updateOverviewImage();
957 public void paintComponent(Graphics g)
959 invalidate(); // needed so that the id width adjuster works correctly
960 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
961 int idWidth = d.width;
963 // check wrapped alignment as at least 1 residue width
964 if (av.getWrapAlignment())
966 SeqCanvas sc = this.getSeqPanel().seqCanvas;
967 if (sc != null && sc.getWidth() < sc.getMinimumWrappedCanvasWidth())
969 // need to make some adjustments
970 idWidth -= (sc.getMinimumWrappedCanvasWidth() - sc.getWidth());
971 av.setIdWidth(idWidth);
972 av.getAlignPanel().getIdPanel().getIdCanvas()
973 .setManuallyAdjusted(true);
975 validateAnnotationDimensions(false);
979 idPanelHolder.setPreferredSize(new Dimension(idWidth, d.height));
980 hscrollFillerPanel.setPreferredSize(new Dimension(idWidth, 12));
982 validate(); // needed so that the id width adjuster works correctly
985 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
986 * though I still think this call should be elsewhere.
988 ViewportRanges ranges = av.getRanges();
989 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
990 super.paintComponent(g);
994 * Set vertical scroll bar position, and number of increments, for wrapped
997 * @param topLeftColumn
998 * the column position at top left (0..)
1000 private void setScrollingForWrappedPanel(int topLeftColumn)
1002 ViewportRanges ranges = av.getRanges();
1003 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
1004 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
1007 * a scrollbar's value can be set to at most (maximum-extent)
1008 * so we add extent (1) to the maxScroll value
1010 vscroll.setUnitIncrement(1);
1011 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
1024 * @return DOCUMENT ME!
1026 * @throws PrinterException
1030 public int print(Graphics pg, PageFormat pf, int pi)
1031 throws PrinterException
1033 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
1035 int pwidth = (int) pf.getImageableWidth();
1036 int pheight = (int) pf.getImageableHeight();
1038 if (av.getWrapAlignment())
1040 return printWrappedAlignment(pwidth, pheight, pi, pg);
1044 return printUnwrapped(pwidth, pheight, pi, pg, pg);
1049 * Draws the alignment image, including sequence ids, sequences, and
1050 * annotation labels and annotations if shown, on either one or two Graphics
1060 * the graphics context for sequence ids and annotation labels
1061 * @param alignmentGraphics
1062 * the graphics context for sequences and annotations (may or may not
1063 * be the same context as idGraphics)
1065 * @throws PrinterException
1067 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
1068 Graphics idGraphics, Graphics alignmentGraphics)
1069 throws PrinterException
1071 final int idWidth, idWidthForGui;
1072 // otherwise calculate it
1073 idWidth = getVisibleIdWidth(false);
1074 // if (getIdPanel()!=null && getIdPanel().getWidth()>0)
1076 // // use the current IdPanel's width, if its set and non-zero
1077 // idWidthForGui = getIdPanel().getWidth();
1082 * Get the horizontal offset to where we draw the sequences.
1083 * This is idWidth if using a single Graphics context, else zero.
1085 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
1088 FontMetrics fm = getFontMetrics(av.getFont());
1089 final int charHeight = av.getCharHeight();
1090 final int scaleHeight = charHeight + fm.getDescent();
1092 idGraphics.setColor(Color.white);
1093 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1094 idGraphics.setFont(av.getFont());
1097 * How many sequences and residues can we fit on a printable page?
1099 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1101 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1103 final int alignmentWidth = av.getAlignment().getVisibleWidth();
1104 int pagesWide = (alignmentWidth / totalRes) + 1;
1106 final int startRes = (pageIndex % pagesWide) * totalRes;
1107 final int endRes = Math.min(startRes + totalRes - 1,
1108 alignmentWidth - 1);
1110 final int startSeq = (pageIndex / pagesWide) * totalSeq;
1111 final int alignmentHeight = av.getAlignment().getHeight();
1112 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
1114 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1116 if (av.isShowAnnotation())
1118 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1121 pagesHigh /= pageHeight;
1123 if (pageIndex >= (pagesWide * pagesHigh))
1125 return Printable.NO_SUCH_PAGE;
1127 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1129 alignmentGraphics.setColor(Color.white);
1130 alignmentGraphics.fillRect(0, 0, pageWidth, pageHeight + scaleHeight);
1133 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1135 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1136 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1137 pageWidth - idWidth, scaleHeight);
1138 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1141 * Draw the sequence ids, offset for scale height,
1142 * then reset to top left (0, 0)
1144 idGraphics.translate(0, scaleHeight);
1145 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1146 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1147 : av.getSelectionGroup().getSequences(null);
1149 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1150 selection, false, idWidth);
1152 idGraphics.setFont(av.getFont());
1153 idGraphics.translate(0, -scaleHeight);
1156 * draw the sequences, offset for scale height, and id width (if using a
1157 * single graphics context), then reset to (0, scale height)
1159 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1160 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1161 startRes, endRes, startSeq, endSeq - 1);
1162 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1164 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1167 * draw annotation labels; drawComponent() translates by
1168 * getScrollOffset(), so compensate for that first;
1169 * then reset to (0, scale height)
1171 int offset = getAlabels().getScrollOffset();
1172 idGraphics.translate(0, -offset);
1173 idGraphics.translate(0, alignmentDrawnHeight);
1174 getAlabels().drawComponentNotGUI(idGraphics, idWidth);
1175 idGraphics.translate(0, -alignmentDrawnHeight);
1178 * draw the annotations starting at
1179 * (idOffset, alignmentHeight) from (0, scaleHeight)
1181 alignmentGraphics.translate(alignmentGraphicsOffset,
1182 alignmentDrawnHeight);
1184 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1185 alignmentGraphics, -1, startRes, endRes + 1);
1188 return Printable.PAGE_EXISTS;
1192 * Prints one page of an alignment in wrapped mode. Returns
1193 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1194 * no page could be drawn (page number out of range).
1204 * @throws PrinterException
1206 public int printWrappedAlignment(int pageWidth, int pageHeight,
1207 int pageNumber, Graphics g) throws PrinterException
1209 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1211 int annotationHeight = 0;
1212 if (av.isShowAnnotation())
1214 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1217 int hgap = av.getCharHeight();
1218 if (av.getScaleAboveWrapped())
1220 hgap += av.getCharHeight();
1223 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1226 int idWidth = getVisibleIdWidth(false);
1228 int maxwidth = av.getAlignment().getVisibleWidth();
1230 int resWidth = getSeqPanel().seqCanvas
1231 .getWrappedCanvasWidth(pageWidth - idWidth);
1232 av.getRanges().setViewportStartAndWidth(0, resWidth);
1234 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1236 g.setColor(Color.white);
1237 g.fillRect(0, 0, pageWidth, pageHeight);
1238 g.setFont(av.getFont());
1239 g.setColor(Color.black);
1242 * method: print the whole wrapped alignment, but with a clip region that
1243 * is restricted to the requested page; this supports selective print of
1244 * single pages or ranges, (at the cost of repeated processing in the
1245 * 'normal' case, when all pages are printed)
1247 g.translate(0, -pageNumber * pageHeight);
1249 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1252 * draw sequence ids and annotation labels (if shown)
1254 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1255 idCanvas.drawIdsWrappedNoGUI((Graphics2D) g, av, 0, totalHeight);
1257 g.translate(idWidth, 0);
1259 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1260 pageWidth - idWidth, totalHeight, 0);
1262 if ((pageNumber * pageHeight) < totalHeight)
1264 return Printable.PAGE_EXISTS;
1268 return Printable.NO_SUCH_PAGE;
1273 * get current sequence ID panel width, or nominal value if panel were to be
1274 * displayed using default settings
1278 public int getVisibleIdWidth()
1280 return getVisibleIdWidth(true);
1284 * get current sequence ID panel width, or nominal value if panel were to be
1285 * displayed using default settings
1288 * indicate if the Id width for onscreen or offscreen display should
1292 protected int getVisibleIdWidth(boolean onscreen)
1294 // see if rendering offscreen - check preferences and calc width accordingly
1295 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1297 return calculateIdWidth(-1, true, true).width;
1299 Integer idwidth = onscreen ? null
1300 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1301 if (idwidth != null)
1303 return idwidth.intValue() + ID_WIDTH_PADDING;
1306 // int w = getIdPanel().getWidth();
1307 // w = calculateIdWidth(-1, true, true).width;
1308 int w = calculateIdWidth(-1, true, true).width;
1309 return (w > 0 ? w : calculateIdWidth().width);
1312 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer)
1313 throws ImageOutputException
1315 makeAlignmentImage(type, file, renderer,
1316 BitmapImageSizing.defaultBitmapImageSizing());
1320 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1321 * writes it to the specified file
1325 * @param textrenderer
1326 * @param bitmapscale
1328 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer,
1329 BitmapImageSizing userBis) throws ImageOutputException
1331 final int borderBottomOffset = 5;
1333 AlignmentDimension aDimension = getAlignmentDimension();
1335 // todo use a lambda function in place of callback here?
1336 ImageWriterI writer = new ImageWriterI()
1339 public void exportImage(Graphics graphics) throws Exception
1341 if (av.getWrapAlignment())
1343 printWrappedAlignment(aDimension.getWidth(),
1344 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1348 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1349 graphics, graphics);
1354 String fileTitle = alignFrame.getTitle();
1355 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1357 int imageWidth = aDimension.getWidth();
1358 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1359 String of = MessageManager.getString("label.alignment");
1360 exporter.doExport(file, this, imageWidth, imageHeight, of, renderer,
1365 * Calculates and returns a suitable width and height (in pixels) for an
1370 public AlignmentDimension getAlignmentDimension()
1372 int maxwidth = av.getAlignment().getVisibleWidth();
1374 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1375 + getScalePanel().getHeight();
1376 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1378 if (av.getWrapAlignment())
1380 height = getWrappedHeight();
1381 if (Jalview.isHeadlessMode())
1383 // need to obtain default alignment width and then add in any
1384 // additional allowance for id margin
1385 // this duplicates the calculation in getWrappedHeight but adjusts for
1386 // offscreen idWidth
1387 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1388 - alignFrame.getInsets().left - alignFrame.getInsets().right
1389 - getVisibleIdWidth() + getVisibleIdWidth(false);
1393 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1397 else if (av.isShowAnnotation())
1399 height += getAnnotationPanel().adjustPanelHeight() + 3;
1401 return new AlignmentDimension(width, height);
1405 public void makePNGImageMap(File imgMapFile, String imageName)
1406 throws ImageOutputException
1408 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1409 // ////////////////////////////////////////////
1410 int idWidth = getVisibleIdWidth(false);
1411 FontMetrics fm = getFontMetrics(av.getFont());
1412 int scaleHeight = av.getCharHeight() + fm.getDescent();
1415 // ////////////////////////////////
1416 if (imgMapFile != null)
1420 int sSize = av.getAlignment().getHeight();
1421 int alwidth = av.getAlignment().getWidth();
1422 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1423 out.println(HTMLOutput.getImageMapHTML());
1424 out.println("<img src=\"" + imageName
1425 + "\" border=\"0\" usemap=\"#Map\" >"
1426 + "<map name=\"Map\">");
1428 for (int s = 0; s < sSize; s++)
1430 int sy = s * av.getCharHeight() + scaleHeight;
1432 SequenceI seq = av.getAlignment().getSequenceAt(s);
1433 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1434 for (int column = 0; column < alwidth; column++)
1436 StringBuilder text = new StringBuilder(512);
1437 String triplet = null;
1438 if (av.getAlignment().isNucleotide())
1440 triplet = ResidueProperties.nucleotideName
1441 .get(seq.getCharAt(column) + "");
1445 triplet = ResidueProperties.aa2Triplet
1446 .get(seq.getCharAt(column) + "");
1449 if (triplet == null)
1454 int seqPos = seq.findPosition(column);
1455 int gSize = groups.length;
1456 for (int g = 0; g < gSize; g++)
1458 if (text.length() < 1)
1460 text.append("<area shape=\"rect\" coords=\"")
1461 .append((idWidth + column * av.getCharWidth()))
1462 .append(",").append(sy).append(",")
1464 + (column + 1) * av.getCharWidth()))
1465 .append(",").append((av.getCharHeight() + sy))
1466 .append("\"").append(" onMouseOver=\"toolTip('")
1467 .append(seqPos).append(" ").append(triplet);
1470 if (groups[g].getStartRes() < column
1471 && groups[g].getEndRes() > column)
1473 text.append("<br><em>").append(groups[g].getName())
1478 if (text.length() < 1)
1480 text.append("<area shape=\"rect\" coords=\"")
1481 .append((idWidth + column * av.getCharWidth()))
1482 .append(",").append(sy).append(",")
1483 .append((idWidth + (column + 1) * av.getCharWidth()))
1484 .append(",").append((av.getCharHeight() + sy))
1485 .append("\"").append(" onMouseOver=\"toolTip('")
1486 .append(seqPos).append(" ").append(triplet);
1488 if (!Comparison.isGap(seq.getCharAt(column)))
1490 List<SequenceFeature> features = seq.findFeatures(column,
1492 for (SequenceFeature sf : features)
1494 if (sf.isContactFeature())
1496 text.append("<br>").append(sf.getType()).append(" ")
1497 .append(sf.getBegin()).append(":")
1498 .append(sf.getEnd());
1502 text.append("<br>");
1503 text.append(sf.getType());
1504 String description = sf.getDescription();
1505 if (description != null
1506 && !sf.getType().equals(description))
1508 description = description.replace("\"", """);
1509 text.append(" ").append(description);
1512 String status = sf.getStatus();
1513 if (status != null && !"".equals(status))
1515 text.append(" (").append(status).append(")");
1518 if (text.length() > 1)
1520 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1521 out.println(text.toString());
1526 out.println("</map></body></html>");
1529 } catch (Exception ex)
1531 throw new ImageOutputException(
1532 "couldn't write ImageMap due to unexpected error", ex);
1534 } // /////////END OF IMAGE MAP
1539 * Answers the height of the entire alignment in pixels, assuming it is in
1544 int getWrappedHeight()
1546 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1548 if (Jalview.isHeadlessMode())
1550 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1551 - vscroll.getPreferredSize().width
1552 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1555 int chunkWidth = getSeqPanel().seqCanvas
1556 .getWrappedCanvasWidth(seqPanelWidth);
1558 int hgap = av.getCharHeight();
1559 if (av.getScaleAboveWrapped())
1561 hgap += av.getCharHeight();
1564 int annotationHeight = 0;
1565 if (av.isShowAnnotation())
1567 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1568 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1571 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1574 int maxwidth = av.getAlignment().getWidth();
1575 if (av.hasHiddenColumns())
1577 maxwidth = av.getAlignment().getHiddenColumns()
1578 .absoluteToVisibleColumn(maxwidth) - 1;
1581 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1587 * close the panel - deregisters all listeners and nulls any references to
1590 public void closePanel()
1592 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1593 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1594 PaintRefresher.RemoveComponent(this);
1599 * try to ensure references are nulled
1601 if (annotationPanel != null)
1603 annotationPanel.dispose();
1604 annotationPanel = null;
1609 av.removePropertyChangeListener(propertyChangeListener);
1610 propertyChangeListener = null;
1611 StructureSelectionManager ssm = av.getStructureSelectionManager();
1612 ssm.removeStructureViewerListener(getSeqPanel(), null);
1613 ssm.removeSelectionListener(getSeqPanel());
1614 ssm.removeCommandListener(av);
1615 ssm.removeStructureViewerListener(getSeqPanel(), null);
1616 ssm.removeSelectionListener(getSeqPanel());
1622 if (Console.isDebugEnabled())
1624 Console.warn("Closing alignment panel which is already closed.");
1630 * Close any open dialogs that would be orphaned when this one is closed
1632 protected void closeChildFrames()
1634 if (overviewPanel != null)
1636 overviewPanel.dispose();
1637 overviewPanel = null;
1639 if (calculationDialog != null)
1641 calculationDialog.closeFrame();
1642 calculationDialog = null;
1647 * hides or shows dynamic annotation rows based on groups and av state flags
1649 public void updateAnnotation()
1651 updateAnnotation(false, false);
1654 public void updateAnnotation(boolean applyGlobalSettings)
1656 updateAnnotation(applyGlobalSettings, false);
1659 public void updateAnnotation(boolean applyGlobalSettings,
1660 boolean preserveNewGroupSettings)
1662 av.updateGroupAnnotationSettings(applyGlobalSettings,
1663 preserveNewGroupSettings);
1664 adjustAnnotationHeight();
1668 public AlignmentI getAlignment()
1670 return av == null ? null : av.getAlignment();
1674 public String getViewName()
1676 return av.getViewName();
1680 * Make/Unmake this alignment panel the current input focus
1684 public void setSelected(boolean b)
1688 if (alignFrame.getSplitViewContainer() != null)
1691 * bring enclosing SplitFrame to front first if there is one
1693 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1695 alignFrame.setSelected(b);
1696 } catch (Exception ex)
1701 setAlignFrameView();
1705 public void setAlignFrameView()
1707 alignFrame.setDisplayedView(this);
1711 public StructureSelectionManager getStructureSelectionManager()
1713 return av.getStructureSelectionManager();
1717 public void raiseOOMWarning(String string, OutOfMemoryError error)
1719 new OOMWarning(string, error, this);
1723 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1726 return new FeatureRenderer(this);
1730 public jalview.api.FeatureRenderer getFeatureRenderer()
1732 return seqPanel.seqCanvas.getFeatureRenderer();
1735 public void updateFeatureRenderer(
1736 jalview.renderer.seqfeatures.FeatureRenderer fr)
1738 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1741 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1743 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1745 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1749 public ScalePanel getScalePanel()
1754 public void setScalePanel(ScalePanel scalePanel)
1756 this.scalePanel = scalePanel;
1759 public SeqPanel getSeqPanel()
1764 public void setSeqPanel(SeqPanel seqPanel)
1766 this.seqPanel = seqPanel;
1769 public AnnotationPanel getAnnotationPanel()
1771 return annotationPanel;
1774 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1776 this.annotationPanel = annotationPanel;
1779 public AnnotationLabels getAlabels()
1784 public void setAlabels(AnnotationLabels alabels)
1786 this.alabels = alabels;
1789 public IdPanel getIdPanel()
1794 public void setIdPanel(IdPanel idPanel)
1796 this.idPanel = idPanel;
1800 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1801 * The aim is to keep the two alignments 'lined up' on their centre columns.
1804 * holds mapped region(s) of this alignment that we are scrolling
1805 * 'to'; may be modified for sequence offset by this method
1806 * @param verticalOffset
1807 * the number of visible sequences to show above the mapped region
1809 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1811 scrollToPosition(sr, verticalOffset, true);
1815 * Set a flag to say do not scroll any (cDNA/protein) complement.
1819 protected void setToScrollComplementPanel(boolean b)
1821 this.scrollComplementaryPanel = b;
1825 * Get whether to scroll complement panel
1827 * @return true if cDNA/protein complement panels should be scrolled
1829 protected boolean isSetToScrollComplementPanel()
1831 return this.scrollComplementaryPanel;
1837 * @adjustHeight if true, try to recalculate panel height for visible
1840 protected void refresh(boolean adjustHeight)
1842 validateAnnotationDimensions(adjustHeight);
1846 // sort, repaint, update overview
1847 paintAlignment(true, false);
1851 // lightweight repaint
1858 * Property change event fired when a change is made to the viewport ranges
1859 * object associated with this alignment panel's viewport
1861 public void propertyChange(PropertyChangeEvent evt)
1863 // update this panel's scroll values based on the new viewport ranges values
1864 ViewportRanges ranges = av.getRanges();
1865 int x = ranges.getStartRes();
1866 int y = ranges.getStartSeq();
1867 setScrollValues(x, y);
1869 // now update any complementary alignment (its viewport ranges object
1870 // is different so does not get automatically updated)
1871 if (isSetToScrollComplementPanel())
1873 setToScrollComplementPanel(false);
1874 av.scrollComplementaryAlignment();
1875 setToScrollComplementPanel(true);
1880 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1881 * reference should be nulled when the dialog is closed.
1883 * @param calculationChooser
1885 public void setCalculationDialog(CalculationChooser calculationChooser)
1887 calculationDialog = calculationChooser;
1891 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1894 public CalculationChooser getCalculationDialog()
1896 return calculationDialog;
1900 * Constructs and sets the title for the Overview window (if there is one),
1901 * including the align frame's title, and view name (if applicable). Returns
1902 * the title, or null if this panel has no Overview window open.
1907 public String setOverviewTitle(AlignFrame alignFrame)
1909 if (this.overviewPanel == null)
1913 String overviewTitle = MessageManager
1914 .formatMessage("label.overview_params", new Object[]
1915 { alignFrame.getTitle() });
1916 String viewName = getViewName();
1917 if (viewName != null)
1919 overviewTitle += (" " + viewName);
1921 overviewPanel.setTitle(overviewTitle);
1922 return overviewTitle;
1926 * If this alignment panel has an Overview panel open, closes it
1928 public void closeOverviewPanel()
1930 if (overviewPanel != null)
1932 overviewPanel.close();
1933 overviewPanel = null;