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.AlignmentAnnotation;
54 import jalview.datamodel.AlignmentI;
55 import jalview.datamodel.HiddenColumns;
56 import jalview.datamodel.SearchResultsI;
57 import jalview.datamodel.SequenceFeature;
58 import jalview.datamodel.SequenceGroup;
59 import jalview.datamodel.SequenceI;
60 import jalview.gui.ImageExporter.ImageWriterI;
61 import jalview.io.HTMLOutput;
62 import jalview.io.exceptions.ImageOutputException;
63 import jalview.jbgui.GAlignmentPanel;
64 import jalview.math.AlignmentDimension;
65 import jalview.schemes.ResidueProperties;
66 import jalview.structure.StructureSelectionManager;
67 import jalview.util.Comparison;
68 import jalview.util.ImageMaker;
69 import jalview.util.MessageManager;
70 import jalview.util.imagemaker.BitmapImageSizing;
71 import jalview.viewmodel.ViewportListenerI;
72 import jalview.viewmodel.ViewportRanges;
78 * @version $Revision: 1.161 $
80 @SuppressWarnings("serial")
81 public class AlignmentPanel extends GAlignmentPanel implements
82 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
85 * spare space in pixels between sequence id and alignment panel
87 private static final int ID_WIDTH_PADDING = 4;
89 public AlignViewport av;
91 OverviewPanel overviewPanel;
93 private SeqPanel seqPanel;
95 private IdPanel idPanel;
97 IdwidthAdjuster idwidthAdjuster;
99 public AlignFrame alignFrame;
101 private ScalePanel scalePanel;
103 private AnnotationPanel annotationPanel;
105 private AnnotationLabels alabels;
107 private int hextent = 0;
109 private int vextent = 0;
112 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
113 * false, suppresses invoking the same method recursively.
115 private boolean scrollComplementaryPanel = true;
117 private PropertyChangeListener propertyChangeListener;
119 private CalculationChooser calculationDialog;
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));
137 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
138 idwidthAdjuster = new IdwidthAdjuster(this);
139 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
141 setAnnotationPanel(new AnnotationPanel(this));
142 setAlabels(new AnnotationLabels(this));
144 annotationScroller.setViewportView(getAnnotationPanel());
145 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
147 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
148 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
150 setScrollValues(0, 0);
152 hscroll.addAdjustmentListener(this);
153 vscroll.addAdjustmentListener(this);
155 addComponentListener(new ComponentAdapter()
158 public void componentResized(ComponentEvent evt)
160 // reset the viewport ranges when the alignment panel is resized
161 // in particular, this initialises the end residue value when Jalview
163 ViewportRanges ranges = av.getRanges();
164 if (av.getWrapAlignment())
166 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
167 getSeqPanel().seqCanvas.getWidth());
168 ranges.setViewportWidth(widthInRes);
172 int widthInRes = getSeqPanel().seqCanvas.getWidth()
174 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
175 / av.getCharHeight();
177 ranges.setViewportWidth(widthInRes);
178 ranges.setViewportHeight(heightInSeq);
184 final AlignmentPanel ap = this;
185 propertyChangeListener = new PropertyChangeListener()
188 public void propertyChange(PropertyChangeEvent evt)
190 if (evt.getPropertyName().equals("alignment"))
192 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
197 av.addPropertyChangeListener(propertyChangeListener);
199 av.getRanges().addPropertyChangeListener(this);
201 adjustAnnotationHeight();
206 public AlignViewportI getAlignViewport()
211 public void alignmentChanged()
213 av.alignmentChanged(this);
215 if (getCalculationDialog() != null)
217 getCalculationDialog().validateCalcTypes();
220 alignFrame.updateEditMenuBar();
222 // no idea if we need to update structure
223 paintAlignment(true, true);
230 public void fontChanged()
232 // set idCanvas bufferedImage to null
233 // to prevent drawing old image
234 FontMetrics fm = getFontMetrics(av.getFont());
236 // update the flag controlling whether the grid is too small to render the
238 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
240 scalePanelHolder.setPreferredSize(
241 new Dimension(10, av.getCharHeight() + fm.getDescent()));
242 idSpaceFillerPanel1.setPreferredSize(
243 new Dimension(10, av.getCharHeight() + fm.getDescent()));
244 idwidthAdjuster.invalidate();
245 scalePanelHolder.invalidate();
246 // BH 2018 getIdPanel().getIdCanvas().gg = null;
247 getSeqPanel().seqCanvas.img = null;
248 getAnnotationPanel().adjustPanelHeight();
250 Dimension d = calculateIdWidth();
251 getIdPanel().getIdCanvas().setPreferredSize(d);
252 hscrollFillerPanel.setPreferredSize(d);
258 * Calculates the width of the alignment labels based on the displayed names
259 * and any bounds on label width set in preferences. The calculated width is
260 * also set as a property of the viewport.
262 * @return Dimension giving the maximum width of the alignment label panel
263 * that should be used.
265 public Dimension calculateIdWidth()
267 int oldWidth = av.getIdWidth();
269 // calculate sensible default width when no preference is available
271 if (av.getIdWidth() < 0)
273 r = calculateDefaultAlignmentIdWidth();
274 av.setIdWidth(r.width);
279 r.width = av.getIdWidth();
284 * fudge: if desired width has changed, update layout
285 * (see also paintComponent - updates layout on a repaint)
287 if (r.width != oldWidth)
289 idPanelHolder.setPreferredSize(r);
295 public Dimension calculateDefaultAlignmentIdWidth()
297 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
298 int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
299 int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
300 return calculateIdWidth(-1, false, false);
304 * Calculate the width of the alignment labels based on the displayed names
305 * and any bounds on label width set in preferences. Also includes annotations
306 * not actually visible.
308 * FIXME JAL-244 JAL-4091 - doesn't include sequence associated annotation
309 * label decorators and only called during tests
312 * -1 or maximum width allowed for IdWidth
313 * @return Dimension giving the maximum width of the alignment label panel
314 * that should be used.
316 protected Dimension calculateIdWidth(int maxwidth)
318 return calculateIdWidth(maxwidth, true, false);
321 * Calculate the width of the alignment labels based on the displayed names
322 * and any bounds on label width set in preferences.
325 * -1 or maximum width allowed for IdWidth
326 * @param includeAnnotations - when true includes width of any additional marks in annotation id panel
327 * @param visibleOnly -
328 * @return Dimension giving the maximum width of the alignment label panel
329 * that should be used.
331 public Dimension calculateIdWidth(int maxwidth,
332 boolean includeAnnotations, boolean visibleOnly)
334 Container c = new Container();
336 FontMetrics fm = c.getFontMetrics(
337 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
339 AlignmentI al = av.getAlignment();
343 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
345 SequenceI s = al.getSequenceAt(i);
346 String id = s.getDisplayId(av.getShowJVSuffix());
347 int stringWidth = fm.stringWidth(id);
348 idWidth = Math.max(idWidth, stringWidth);
352 // Also check annotation label widths
353 if (includeAnnotations && al.getAlignmentAnnotation() != null)
355 AnnotationLabels aal = getAlabels();
356 int stringWidth = aal.drawLabels(null, false, idWidth, false, false,
358 idWidth = Math.max(idWidth, stringWidth);
361 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
362 w += ID_WIDTH_PADDING;
364 return new Dimension(w, 12);
368 * Highlight the given results on the alignment
371 public void highlightSearchResults(SearchResultsI results)
373 boolean scrolled = scrollToPosition(results, 0, false);
375 boolean fastPaint = !(scrolled && av.getWrapAlignment());
377 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
381 * Scroll the view to show the position of the highlighted region in results
384 * @param searchResults
387 public boolean scrollToPosition(SearchResultsI searchResults)
389 return scrollToPosition(searchResults, 0, false);
393 * Scrolls the view (if necessary) to show the position of the first
394 * highlighted region in results (if any). Answers true if the view was
395 * scrolled, or false if no matched region was found, or it is already
399 * @param verticalOffset
400 * if greater than zero, allows scrolling to a position below the
401 * first displayed sequence
403 * if true, try to centre the search results horizontally in the view
406 protected boolean scrollToPosition(SearchResultsI results,
407 int verticalOffset, boolean centre)
409 int startv, endv, starts, ends;
410 ViewportRanges ranges = av.getRanges();
412 if (results == null || results.isEmpty() || av == null
413 || av.getAlignment() == null)
417 int seqIndex = av.getAlignment().findIndex(results);
422 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
424 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
433 * To centre results, scroll to positions half the visible width
434 * left/right of the start/end positions
438 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
439 start = Math.max(start - offset, 0);
440 end = end + offset - 1;
446 if (end == seq.getEnd())
451 if (av.hasHiddenColumns())
453 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
454 start = hidden.absoluteToVisibleColumn(start);
455 end = hidden.absoluteToVisibleColumn(end);
458 if (!hidden.isVisible(r[0]))
460 // don't scroll - position isn't visible
467 * allow for offset of target sequence (actually scroll to one above it)
469 seqIndex = Math.max(0, seqIndex - verticalOffset);
470 boolean scrollNeeded = true;
472 if (!av.getWrapAlignment())
474 if ((startv = ranges.getStartRes()) >= start)
477 * Scroll left to make start of search results visible
479 setScrollValues(start, seqIndex);
481 else if ((endv = ranges.getEndRes()) <= end)
484 * Scroll right to make end of search results visible
486 setScrollValues(startv + end - endv, seqIndex);
488 else if ((starts = ranges.getStartSeq()) > seqIndex)
491 * Scroll up to make start of search results visible
493 setScrollValues(ranges.getStartRes(), seqIndex);
495 else if ((ends = ranges.getEndSeq()) <= seqIndex)
498 * Scroll down to make end of search results visible
500 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
503 * Else results are already visible - no need to scroll
505 scrollNeeded = false;
509 scrollNeeded = ranges.scrollToWrappedVisible(start);
512 paintAlignment(false, false);
520 * @return DOCUMENT ME!
522 public OverviewPanel getOverviewPanel()
524 return overviewPanel;
533 public void setOverviewPanel(OverviewPanel op)
541 * Hide or show annotation panel
544 public void setAnnotationVisible(boolean b)
546 if (!av.getWrapAlignment())
548 annotationSpaceFillerHolder.setVisible(b);
549 annotationScroller.setVisible(b);
555 * automatically adjust annotation panel height for new annotation whilst
556 * ensuring the alignment is still visible.
559 public void adjustAnnotationHeight()
561 // TODO: display vertical annotation scrollbar if necessary
562 // this is called after loading new annotation onto alignment
563 if (alignFrame.getHeight() == 0)
565 jalview.bin.Console.outPrintln("NEEDS FIXING");
567 validateAnnotationDimensions(true);
569 // TODO: many places call this method and also paintAlignment with various
570 // different settings. this means multiple redraws are triggered...
571 paintAlignment(true, av.needToUpdateStructureViews());
575 * calculate the annotation dimensions and refresh slider values accordingly.
576 * need to do repaints/notifys afterwards.
578 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
580 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
581 // are not changing ancestors, and keyboard action listeners do
582 // not need to be reset. addNotify() is a very expensive operation,
583 // requiring a full re-layout of all parents and children.
584 // Note in JComponent:
585 // This method is called by the toolkit internally and should
586 // not be called directly by programs.
587 // I note that addNotify() is called in several areas of Jalview.
589 AnnotationPanel ap = getAnnotationPanel();
590 int annotationHeight = ap.adjustPanelHeight();
591 annotationHeight = ap.adjustForAlignFrame(adjustPanelHeight,
595 Dimension e = idPanel.getSize();
596 int idWidth = e.width;
597 boolean manuallyAdjusted = this.getIdPanel().getIdCanvas()
599 annotationScroller.setPreferredSize(new Dimension(
600 manuallyAdjusted ? idWidth : annotationScroller.getWidth(),
603 alabels.setPreferredSize(new Dimension(idWidth, annotationHeight));
605 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
606 manuallyAdjusted ? idWidth
607 : annotationSpaceFillerHolder.getWidth(),
609 annotationScroller.validate();
610 annotationScroller.addNotify();
615 * update alignment layout for viewport settings
620 public void updateLayout()
623 setAnnotationVisible(av.isShowAnnotation());
624 boolean wrap = av.getWrapAlignment();
625 ViewportRanges ranges = av.getRanges();
626 ranges.setStartSeq(0);
627 // scalePanelHolder.setVisible(!wrap);
628 hscroll.setVisible(!wrap);
629 // Allow idPanel width adjustment in wrap mode
630 idwidthAdjuster.setVisible(true);
634 annotationScroller.setVisible(false);
635 annotationSpaceFillerHolder.setVisible(false);
637 else if (av.isShowAnnotation())
639 annotationScroller.setVisible(true);
640 annotationSpaceFillerHolder.setVisible(true);
641 validateAnnotationDimensions(false);
644 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
646 { // may not yet be laid out
649 int widthInRes = getSeqPanel().seqCanvas
650 .getWrappedCanvasWidth(canvasWidth);
651 ranges.setViewportWidth(widthInRes);
655 int widthInRes = (canvasWidth / av.getCharWidth());
656 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
657 / av.getCharHeight());
659 ranges.setViewportWidth(widthInRes);
660 ranges.setViewportHeight(heightInSeq);
664 // idSpaceFillerPanel1.setVisible(!wrap);
670 * Adjust row/column scrollers to show a visible position in the alignment.
673 * visible column to scroll to
675 * visible row to scroll to
678 public void setScrollValues(int xpos, int ypos)
683 if (av == null || av.getAlignment() == null)
688 if (av.getWrapAlignment())
690 setScrollingForWrappedPanel(x);
694 int width = av.getAlignment().getVisibleWidth();
695 int height = av.getAlignment().getHeight();
697 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
698 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
705 if (vextent > height)
710 if ((hextent + x) > width)
715 if ((vextent + y) > height)
717 y = height - vextent;
730 // update the scroll values
731 hscroll.setValues(x, hextent, 0, width);
732 vscroll.setValues(y, vextent, 0, height);
737 * Respond to adjustment event when horizontal or vertical scrollbar is
741 * adjustment event encoding whether hscroll or vscroll changed
744 public void adjustmentValueChanged(AdjustmentEvent evt)
746 if (av.getWrapAlignment())
748 adjustScrollingWrapped(evt);
752 ViewportRanges ranges = av.getRanges();
754 if (evt.getSource() == hscroll)
756 int oldX = ranges.getStartRes();
757 int oldwidth = ranges.getViewportWidth();
758 int x = hscroll.getValue();
759 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
761 // if we're scrolling to the position we're already at, stop
762 // this prevents infinite recursion of events when the scroll/viewport
763 // ranges values are the same
764 if ((x == oldX) && (width == oldwidth))
768 ranges.setViewportStartAndWidth(x, width);
770 else if (evt.getSource() == vscroll)
772 int oldY = ranges.getStartSeq();
773 int oldheight = ranges.getViewportHeight();
774 int y = vscroll.getValue();
775 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
777 // if we're scrolling to the position we're already at, stop
778 // this prevents infinite recursion of events when the scroll/viewport
779 // ranges values are the same
780 if ((y == oldY) && (height == oldheight))
784 ranges.setViewportStartAndHeight(y, height);
790 * Responds to a scroll change by setting the start position of the viewport.
795 protected void adjustScrollingWrapped(AdjustmentEvent evt)
797 if (evt.getSource() == hscroll)
799 return; // no horizontal scroll when wrapped
801 final ViewportRanges ranges = av.getRanges();
803 if (evt.getSource() == vscroll)
805 int newY = vscroll.getValue();
808 * if we're scrolling to the position we're already at, stop
809 * this prevents infinite recursion of events when the scroll/viewport
810 * ranges values are the same
812 int oldX = ranges.getStartRes();
813 int oldY = ranges.getWrappedScrollPosition(oldX);
821 * limit page up/down to one width's worth of positions
823 int rowSize = ranges.getViewportWidth();
824 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
825 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
830 // This is only called if file loaded is a jar file that
831 // was wrapped when saved and user has wrap alignment true
832 // as preference setting
833 SwingUtilities.invokeLater(new Runnable()
838 // When updating scrolling to use ViewportChange events, this code
839 // could not be validated and it is not clear if it is now being
840 // called. Log warning here in case it is called and unforeseen
843 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
845 // scroll to start of panel
846 ranges.setStartRes(0);
847 ranges.setStartSeq(0);
855 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
858 public void paintAlignment(boolean updateOverview,
859 boolean updateStructures)
861 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
862 av.isShowAutocalculatedAbove());
863 sorter.sort(getAlignment().getAlignmentAnnotation(),
864 av.getSortAnnotationsBy());
867 if (updateStructures)
869 av.getStructureSelectionManager().sequenceColoursChanged(this);
874 if (overviewPanel != null)
876 overviewPanel.updateOverviewImage();
882 public void paintComponent(Graphics g)
884 invalidate(); // needed so that the id width adjuster works correctly
885 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
886 int idWidth = d.width;
888 // check wrapped alignment as at least 1 residue width
889 if (av.getWrapAlignment())
891 SeqCanvas sc = this.getSeqPanel().seqCanvas;
892 if (sc != null && sc.getWidth() < sc.getMinimumWrappedCanvasWidth())
894 // need to make some adjustments
895 idWidth -= (sc.getMinimumWrappedCanvasWidth() - sc.getWidth());
896 av.setIdWidth(idWidth);
897 av.getAlignPanel().getIdPanel().getIdCanvas()
898 .setManuallyAdjusted(true);
900 validateAnnotationDimensions(false);
904 idPanelHolder.setPreferredSize(new Dimension(idWidth, d.height));
905 hscrollFillerPanel.setPreferredSize(new Dimension(idWidth, 12));
907 validate(); // needed so that the id width adjuster works correctly
910 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
911 * though I still think this call should be elsewhere.
913 ViewportRanges ranges = av.getRanges();
914 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
915 super.paintComponent(g);
919 * Set vertical scroll bar position, and number of increments, for wrapped
922 * @param topLeftColumn
923 * the column position at top left (0..)
925 private void setScrollingForWrappedPanel(int topLeftColumn)
927 ViewportRanges ranges = av.getRanges();
928 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
929 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
932 * a scrollbar's value can be set to at most (maximum-extent)
933 * so we add extent (1) to the maxScroll value
935 vscroll.setUnitIncrement(1);
936 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
949 * @return DOCUMENT ME!
951 * @throws PrinterException
955 public int print(Graphics pg, PageFormat pf, int pi)
956 throws PrinterException
958 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
960 int pwidth = (int) pf.getImageableWidth();
961 int pheight = (int) pf.getImageableHeight();
963 if (av.getWrapAlignment())
965 return printWrappedAlignment(pwidth, pheight, pi, pg);
969 return printUnwrapped(pwidth, pheight, pi, pg, pg);
974 * Draws the alignment image, including sequence ids, sequences, and
975 * annotation labels and annotations if shown, on either one or two Graphics
985 * the graphics context for sequence ids and annotation labels
986 * @param alignmentGraphics
987 * the graphics context for sequences and annotations (may or may not
988 * be the same context as idGraphics)
990 * @throws PrinterException
992 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
993 Graphics idGraphics, Graphics alignmentGraphics)
994 throws PrinterException
996 final int idWidth, idWidthForGui;
997 // otherwise calculate it
998 idWidth = getVisibleIdWidth(false);
999 // if (getIdPanel()!=null && getIdPanel().getWidth()>0)
1001 // // use the current IdPanel's width, if its set and non-zero
1002 // idWidthForGui = getIdPanel().getWidth();
1007 * Get the horizontal offset to where we draw the sequences.
1008 * This is idWidth if using a single Graphics context, else zero.
1010 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
1013 FontMetrics fm = getFontMetrics(av.getFont());
1014 final int charHeight = av.getCharHeight();
1015 final int scaleHeight = charHeight + fm.getDescent();
1017 idGraphics.setColor(Color.white);
1018 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1019 idGraphics.setFont(av.getFont());
1022 * How many sequences and residues can we fit on a printable page?
1024 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1026 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1028 final int alignmentWidth = av.getAlignment().getVisibleWidth();
1029 int pagesWide = (alignmentWidth / totalRes) + 1;
1031 final int startRes = (pageIndex % pagesWide) * totalRes;
1032 final int endRes = Math.min(startRes + totalRes - 1,
1033 alignmentWidth - 1);
1035 final int startSeq = (pageIndex / pagesWide) * totalSeq;
1036 final int alignmentHeight = av.getAlignment().getHeight();
1037 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
1039 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1041 if (av.isShowAnnotation())
1043 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1046 pagesHigh /= pageHeight;
1048 if (pageIndex >= (pagesWide * pagesHigh))
1050 return Printable.NO_SUCH_PAGE;
1052 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1055 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1057 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1058 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1059 pageWidth - idWidth, scaleHeight);
1060 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1063 * Draw the sequence ids, offset for scale height,
1064 * then reset to top left (0, 0)
1066 idGraphics.translate(0, scaleHeight);
1067 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1068 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1069 : av.getSelectionGroup().getSequences(null);
1071 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1072 selection, false,idWidth);
1074 idGraphics.setFont(av.getFont());
1075 idGraphics.translate(0, -scaleHeight);
1078 * draw the sequences, offset for scale height, and id width (if using a
1079 * single graphics context), then reset to (0, scale height)
1081 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1082 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1083 startRes, endRes, startSeq, endSeq - 1);
1084 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1086 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1089 * draw annotation labels; drawComponent() translates by
1090 * getScrollOffset(), so compensate for that first;
1091 * then reset to (0, scale height)
1093 int offset = getAlabels().getScrollOffset();
1094 idGraphics.translate(0, -offset);
1095 idGraphics.translate(0, alignmentDrawnHeight);
1096 getAlabels().drawComponentNotGUI(idGraphics, idWidth);
1097 idGraphics.translate(0, -alignmentDrawnHeight);
1100 * draw the annotations starting at
1101 * (idOffset, alignmentHeight) from (0, scaleHeight)
1103 alignmentGraphics.translate(alignmentGraphicsOffset,
1104 alignmentDrawnHeight);
1106 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1107 alignmentGraphics, -1, startRes, endRes + 1);
1110 return Printable.PAGE_EXISTS;
1114 * Prints one page of an alignment in wrapped mode. Returns
1115 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1116 * no page could be drawn (page number out of range).
1126 * @throws PrinterException
1128 public int printWrappedAlignment(int pageWidth, int pageHeight,
1129 int pageNumber, Graphics g) throws PrinterException
1131 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1133 int annotationHeight = 0;
1134 if (av.isShowAnnotation())
1136 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1139 int hgap = av.getCharHeight();
1140 if (av.getScaleAboveWrapped())
1142 hgap += av.getCharHeight();
1145 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1148 int idWidth = getVisibleIdWidth(false);
1150 int maxwidth = av.getAlignment().getVisibleWidth();
1152 int resWidth = getSeqPanel().seqCanvas
1153 .getWrappedCanvasWidth(pageWidth - idWidth);
1154 av.getRanges().setViewportStartAndWidth(0, resWidth);
1156 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1158 g.setColor(Color.white);
1159 g.fillRect(0, 0, pageWidth, pageHeight);
1160 g.setFont(av.getFont());
1161 g.setColor(Color.black);
1164 * method: print the whole wrapped alignment, but with a clip region that
1165 * is restricted to the requested page; this supports selective print of
1166 * single pages or ranges, (at the cost of repeated processing in the
1167 * 'normal' case, when all pages are printed)
1169 g.translate(0, -pageNumber * pageHeight);
1171 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1174 * draw sequence ids and annotation labels (if shown)
1176 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1177 idCanvas.drawIdsWrappedNoGUI((Graphics2D) g, av, 0, totalHeight);
1179 g.translate(idWidth, 0);
1181 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1182 pageWidth - idWidth, totalHeight, 0);
1184 if ((pageNumber * pageHeight) < totalHeight)
1186 return Printable.PAGE_EXISTS;
1190 return Printable.NO_SUCH_PAGE;
1195 * get current sequence ID panel width, or nominal value if panel were to be
1196 * displayed using default settings
1200 public int getVisibleIdWidth()
1202 return getVisibleIdWidth(true);
1206 * get current sequence ID panel width, or nominal value if panel were to be
1207 * displayed using default settings
1210 * indicate if the Id width for onscreen or offscreen display should
1214 protected int getVisibleIdWidth(boolean onscreen)
1216 // see if rendering offscreen - check preferences and calc width accordingly
1217 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1219 return calculateIdWidth(-1,true,true).width;
1221 Integer idwidth = onscreen ? null
1222 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1223 if (idwidth != null)
1225 return idwidth.intValue() + ID_WIDTH_PADDING;
1228 int w = getIdPanel().getWidth();
1229 w = this.calculateIdWidth(-1, true, true).width;
1230 return (w > 0 ? w : calculateIdWidth().width);
1233 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer)
1234 throws ImageOutputException
1236 makeAlignmentImage(type, file, renderer,
1237 BitmapImageSizing.defaultBitmapImageSizing());
1241 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1242 * writes it to the specified file
1246 * @param textrenderer
1247 * @param bitmapscale
1249 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer,
1250 BitmapImageSizing userBis) throws ImageOutputException
1252 final int borderBottomOffset = 5;
1254 AlignmentDimension aDimension = getAlignmentDimension();
1256 // todo use a lambda function in place of callback here?
1257 ImageWriterI writer = new ImageWriterI()
1260 public void exportImage(Graphics graphics) throws Exception
1262 if (av.getWrapAlignment())
1264 printWrappedAlignment(aDimension.getWidth(),
1265 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1269 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1270 graphics, graphics);
1275 String fileTitle = alignFrame.getTitle();
1276 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1278 int imageWidth = aDimension.getWidth();
1279 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1280 String of = MessageManager.getString("label.alignment");
1281 exporter.doExport(file, this, imageWidth, imageHeight, of, renderer,
1286 * Calculates and returns a suitable width and height (in pixels) for an
1291 public AlignmentDimension getAlignmentDimension()
1293 int maxwidth = av.getAlignment().getVisibleWidth();
1295 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1296 + getScalePanel().getHeight();
1297 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1299 if (av.getWrapAlignment())
1301 height = getWrappedHeight();
1302 if (Jalview.isHeadlessMode())
1304 // need to obtain default alignment width and then add in any
1305 // additional allowance for id margin
1306 // this duplicates the calculation in getWrappedHeight but adjusts for
1308 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1309 - alignFrame.getInsets().left - alignFrame.getInsets().right
1310 - getVisibleIdWidth() + getVisibleIdWidth(false);
1314 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1318 else if (av.isShowAnnotation())
1320 height += getAnnotationPanel().adjustPanelHeight() + 3;
1322 return new AlignmentDimension(width, height);
1326 public void makePNGImageMap(File imgMapFile, String imageName)
1327 throws ImageOutputException
1329 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1330 // ////////////////////////////////////////////
1331 int idWidth = getVisibleIdWidth(false);
1332 FontMetrics fm = getFontMetrics(av.getFont());
1333 int scaleHeight = av.getCharHeight() + fm.getDescent();
1336 // ////////////////////////////////
1337 if (imgMapFile != null)
1341 int sSize = av.getAlignment().getHeight();
1342 int alwidth = av.getAlignment().getWidth();
1343 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1344 out.println(HTMLOutput.getImageMapHTML());
1345 out.println("<img src=\"" + imageName
1346 + "\" border=\"0\" usemap=\"#Map\" >"
1347 + "<map name=\"Map\">");
1349 for (int s = 0; s < sSize; s++)
1351 int sy = s * av.getCharHeight() + scaleHeight;
1353 SequenceI seq = av.getAlignment().getSequenceAt(s);
1354 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1355 for (int column = 0; column < alwidth; column++)
1357 StringBuilder text = new StringBuilder(512);
1358 String triplet = null;
1359 if (av.getAlignment().isNucleotide())
1361 triplet = ResidueProperties.nucleotideName
1362 .get(seq.getCharAt(column) + "");
1366 triplet = ResidueProperties.aa2Triplet
1367 .get(seq.getCharAt(column) + "");
1370 if (triplet == null)
1375 int seqPos = seq.findPosition(column);
1376 int gSize = groups.length;
1377 for (int g = 0; g < gSize; g++)
1379 if (text.length() < 1)
1381 text.append("<area shape=\"rect\" coords=\"")
1382 .append((idWidth + column * av.getCharWidth()))
1383 .append(",").append(sy).append(",")
1385 + (column + 1) * av.getCharWidth()))
1386 .append(",").append((av.getCharHeight() + sy))
1387 .append("\"").append(" onMouseOver=\"toolTip('")
1388 .append(seqPos).append(" ").append(triplet);
1391 if (groups[g].getStartRes() < column
1392 && groups[g].getEndRes() > column)
1394 text.append("<br><em>").append(groups[g].getName())
1399 if (text.length() < 1)
1401 text.append("<area shape=\"rect\" coords=\"")
1402 .append((idWidth + column * av.getCharWidth()))
1403 .append(",").append(sy).append(",")
1404 .append((idWidth + (column + 1) * av.getCharWidth()))
1405 .append(",").append((av.getCharHeight() + sy))
1406 .append("\"").append(" onMouseOver=\"toolTip('")
1407 .append(seqPos).append(" ").append(triplet);
1409 if (!Comparison.isGap(seq.getCharAt(column)))
1411 List<SequenceFeature> features = seq.findFeatures(column,
1413 for (SequenceFeature sf : features)
1415 if (sf.isContactFeature())
1417 text.append("<br>").append(sf.getType()).append(" ")
1418 .append(sf.getBegin()).append(":")
1419 .append(sf.getEnd());
1423 text.append("<br>");
1424 text.append(sf.getType());
1425 String description = sf.getDescription();
1426 if (description != null
1427 && !sf.getType().equals(description))
1429 description = description.replace("\"", """);
1430 text.append(" ").append(description);
1433 String status = sf.getStatus();
1434 if (status != null && !"".equals(status))
1436 text.append(" (").append(status).append(")");
1439 if (text.length() > 1)
1441 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1442 out.println(text.toString());
1447 out.println("</map></body></html>");
1450 } catch (Exception ex)
1452 throw new ImageOutputException(
1453 "couldn't write ImageMap due to unexpected error", ex);
1455 } // /////////END OF IMAGE MAP
1460 * Answers the height of the entire alignment in pixels, assuming it is in
1465 int getWrappedHeight()
1467 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1469 if (Jalview.isHeadlessMode())
1471 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1472 - vscroll.getPreferredSize().width
1473 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1476 int chunkWidth = getSeqPanel().seqCanvas
1477 .getWrappedCanvasWidth(seqPanelWidth);
1479 int hgap = av.getCharHeight();
1480 if (av.getScaleAboveWrapped())
1482 hgap += av.getCharHeight();
1485 int annotationHeight = 0;
1486 if (av.isShowAnnotation())
1488 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1489 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1492 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1495 int maxwidth = av.getAlignment().getWidth();
1496 if (av.hasHiddenColumns())
1498 maxwidth = av.getAlignment().getHiddenColumns()
1499 .absoluteToVisibleColumn(maxwidth) - 1;
1502 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1508 * close the panel - deregisters all listeners and nulls any references to
1511 public void closePanel()
1513 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1514 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1515 PaintRefresher.RemoveComponent(this);
1520 * try to ensure references are nulled
1522 if (annotationPanel != null)
1524 annotationPanel.dispose();
1525 annotationPanel = null;
1530 av.removePropertyChangeListener(propertyChangeListener);
1531 propertyChangeListener = null;
1532 StructureSelectionManager ssm = av.getStructureSelectionManager();
1533 ssm.removeStructureViewerListener(getSeqPanel(), null);
1534 ssm.removeSelectionListener(getSeqPanel());
1535 ssm.removeCommandListener(av);
1536 ssm.removeStructureViewerListener(getSeqPanel(), null);
1537 ssm.removeSelectionListener(getSeqPanel());
1543 if (Console.isDebugEnabled())
1545 Console.warn("Closing alignment panel which is already closed.");
1551 * Close any open dialogs that would be orphaned when this one is closed
1553 protected void closeChildFrames()
1555 if (overviewPanel != null)
1557 overviewPanel.dispose();
1558 overviewPanel = null;
1560 if (calculationDialog != null)
1562 calculationDialog.closeFrame();
1563 calculationDialog = null;
1568 * hides or shows dynamic annotation rows based on groups and av state flags
1570 public void updateAnnotation()
1572 updateAnnotation(false, false);
1575 public void updateAnnotation(boolean applyGlobalSettings)
1577 updateAnnotation(applyGlobalSettings, false);
1580 public void updateAnnotation(boolean applyGlobalSettings,
1581 boolean preserveNewGroupSettings)
1583 av.updateGroupAnnotationSettings(applyGlobalSettings,
1584 preserveNewGroupSettings);
1585 adjustAnnotationHeight();
1589 public AlignmentI getAlignment()
1591 return av == null ? null : av.getAlignment();
1595 public String getViewName()
1597 return av.getViewName();
1601 * Make/Unmake this alignment panel the current input focus
1605 public void setSelected(boolean b)
1609 if (alignFrame.getSplitViewContainer() != null)
1612 * bring enclosing SplitFrame to front first if there is one
1614 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1616 alignFrame.setSelected(b);
1617 } catch (Exception ex)
1622 setAlignFrameView();
1626 public void setAlignFrameView()
1628 alignFrame.setDisplayedView(this);
1632 public StructureSelectionManager getStructureSelectionManager()
1634 return av.getStructureSelectionManager();
1638 public void raiseOOMWarning(String string, OutOfMemoryError error)
1640 new OOMWarning(string, error, this);
1644 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1647 return new FeatureRenderer(this);
1651 public jalview.api.FeatureRenderer getFeatureRenderer()
1653 return seqPanel.seqCanvas.getFeatureRenderer();
1656 public void updateFeatureRenderer(
1657 jalview.renderer.seqfeatures.FeatureRenderer fr)
1659 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1662 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1664 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1666 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1670 public ScalePanel getScalePanel()
1675 public void setScalePanel(ScalePanel scalePanel)
1677 this.scalePanel = scalePanel;
1680 public SeqPanel getSeqPanel()
1685 public void setSeqPanel(SeqPanel seqPanel)
1687 this.seqPanel = seqPanel;
1690 public AnnotationPanel getAnnotationPanel()
1692 return annotationPanel;
1695 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1697 this.annotationPanel = annotationPanel;
1700 public AnnotationLabels getAlabels()
1705 public void setAlabels(AnnotationLabels alabels)
1707 this.alabels = alabels;
1710 public IdPanel getIdPanel()
1715 public void setIdPanel(IdPanel idPanel)
1717 this.idPanel = idPanel;
1721 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1722 * The aim is to keep the two alignments 'lined up' on their centre columns.
1725 * holds mapped region(s) of this alignment that we are scrolling
1726 * 'to'; may be modified for sequence offset by this method
1727 * @param verticalOffset
1728 * the number of visible sequences to show above the mapped region
1730 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1732 scrollToPosition(sr, verticalOffset, true);
1736 * Set a flag to say do not scroll any (cDNA/protein) complement.
1740 protected void setToScrollComplementPanel(boolean b)
1742 this.scrollComplementaryPanel = b;
1746 * Get whether to scroll complement panel
1748 * @return true if cDNA/protein complement panels should be scrolled
1750 protected boolean isSetToScrollComplementPanel()
1752 return this.scrollComplementaryPanel;
1758 * @adjustHeight if true, try to recalculate panel height for visible
1761 protected void refresh(boolean adjustHeight)
1763 validateAnnotationDimensions(adjustHeight);
1767 // sort, repaint, update overview
1768 paintAlignment(true, false);
1772 // lightweight repaint
1779 * Property change event fired when a change is made to the viewport ranges
1780 * object associated with this alignment panel's viewport
1782 public void propertyChange(PropertyChangeEvent evt)
1784 // update this panel's scroll values based on the new viewport ranges values
1785 ViewportRanges ranges = av.getRanges();
1786 int x = ranges.getStartRes();
1787 int y = ranges.getStartSeq();
1788 setScrollValues(x, y);
1790 // now update any complementary alignment (its viewport ranges object
1791 // is different so does not get automatically updated)
1792 if (isSetToScrollComplementPanel())
1794 setToScrollComplementPanel(false);
1795 av.scrollComplementaryAlignment();
1796 setToScrollComplementPanel(true);
1801 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1802 * reference should be nulled when the dialog is closed.
1804 * @param calculationChooser
1806 public void setCalculationDialog(CalculationChooser calculationChooser)
1808 calculationDialog = calculationChooser;
1812 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1815 public CalculationChooser getCalculationDialog()
1817 return calculationDialog;
1821 * Constructs and sets the title for the Overview window (if there is one),
1822 * including the align frame's title, and view name (if applicable). Returns
1823 * the title, or null if this panel has no Overview window open.
1828 public String setOverviewTitle(AlignFrame alignFrame)
1830 if (this.overviewPanel == null)
1834 String overviewTitle = MessageManager
1835 .formatMessage("label.overview_params", new Object[]
1836 { alignFrame.getTitle() });
1837 String viewName = getViewName();
1838 if (viewName != null)
1840 overviewTitle += (" " + viewName);
1842 overviewPanel.setTitle(overviewTitle);
1843 return overviewTitle;
1847 * If this alignment panel has an Overview panel open, closes it
1849 public void closeOverviewPanel()
1851 if (overviewPanel != null)
1853 overviewPanel.close();
1854 overviewPanel = null;