2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AnnotationSorter;
24 import jalview.api.AlignViewportI;
25 import jalview.api.AlignmentViewPanel;
26 import jalview.api.SequenceRenderer;
27 import jalview.bin.Cache;
28 import jalview.bin.Jalview;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.HiddenColumns;
31 import jalview.datamodel.SearchResultsI;
32 import jalview.datamodel.SequenceFeature;
33 import jalview.datamodel.SequenceGroup;
34 import jalview.datamodel.SequenceI;
35 import jalview.gui.ImageExporter.ImageWriterI;
36 import jalview.io.HTMLOutput;
37 import jalview.jbgui.GAlignmentPanel;
38 import jalview.math.AlignmentDimension;
39 import jalview.schemes.ResidueProperties;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.util.Comparison;
42 import jalview.util.ImageMaker;
43 import jalview.util.MessageManager;
44 import jalview.viewmodel.ViewportListenerI;
45 import jalview.viewmodel.ViewportRanges;
47 import java.awt.BorderLayout;
48 import java.awt.Color;
49 import java.awt.Container;
50 import java.awt.Dimension;
52 import java.awt.FontMetrics;
53 import java.awt.Graphics;
54 import java.awt.Graphics2D;
55 import java.awt.event.AdjustmentEvent;
56 import java.awt.event.AdjustmentListener;
57 import java.awt.event.ComponentAdapter;
58 import java.awt.event.ComponentEvent;
59 import java.awt.print.PageFormat;
60 import java.awt.print.Printable;
61 import java.awt.print.PrinterException;
62 import java.beans.PropertyChangeEvent;
63 import java.beans.PropertyChangeListener;
65 import java.io.FileWriter;
66 import java.io.PrintWriter;
67 import java.util.List;
69 import javax.swing.SwingUtilities;
75 * @version $Revision: 1.161 $
77 @SuppressWarnings("serial")
78 public class AlignmentPanel extends GAlignmentPanel implements
79 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
81 public AlignViewport av;
83 OverviewPanel overviewPanel;
85 private SeqPanel seqPanel;
87 private IdPanel idPanel;
89 IdwidthAdjuster idwidthAdjuster;
91 public AlignFrame alignFrame;
93 private ScalePanel scalePanel;
95 private AnnotationPanel annotationPanel;
97 private AnnotationLabels alabels;
99 private int hextent = 0;
101 private int vextent = 0;
104 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
105 * false, suppresses invoking the same method recursively.
107 private boolean scrollComplementaryPanel = true;
109 private PropertyChangeListener propertyChangeListener;
111 private CalculationChooser calculationDialog;
114 * Creates a new AlignmentPanel object.
119 public AlignmentPanel(AlignFrame af, final AlignViewport av)
121 // setBackground(Color.white); // BH 2019
124 setSeqPanel(new SeqPanel(av, this));
125 setIdPanel(new IdPanel(av, this));
127 setScalePanel(new ScalePanel(av, this));
129 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
130 idwidthAdjuster = new IdwidthAdjuster(this);
131 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
133 setAnnotationPanel(new AnnotationPanel(this));
134 setAlabels(new AnnotationLabels(this));
136 annotationScroller.setViewportView(getAnnotationPanel());
137 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
139 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
140 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
142 setScrollValues(0, 0);
144 hscroll.addAdjustmentListener(this);
145 vscroll.addAdjustmentListener(this);
147 addComponentListener(new ComponentAdapter()
150 public void componentResized(ComponentEvent evt)
152 // reset the viewport ranges when the alignment panel is resized
153 // in particular, this initialises the end residue value when Jalview
155 ViewportRanges ranges = av.getRanges();
156 if (av.getWrapAlignment())
158 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
159 getSeqPanel().seqCanvas.getWidth());
160 ranges.setViewportWidth(widthInRes);
164 int widthInRes = getSeqPanel().seqCanvas.getWidth()
166 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
167 / av.getCharHeight();
169 ranges.setViewportWidth(widthInRes);
170 ranges.setViewportHeight(heightInSeq);
176 final AlignmentPanel ap = this;
177 propertyChangeListener = new PropertyChangeListener()
180 public void propertyChange(PropertyChangeEvent evt)
182 if (evt.getPropertyName().equals("alignment"))
184 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
189 av.addPropertyChangeListener(propertyChangeListener);
191 av.getRanges().addPropertyChangeListener(this);
193 adjustAnnotationHeight();
198 public AlignViewportI getAlignViewport()
203 public void alignmentChanged()
205 av.alignmentChanged(this);
207 if (getCalculationDialog() != null)
209 getCalculationDialog().validateCalcTypes();
212 alignFrame.updateEditMenuBar();
214 // no idea if we need to update structure
215 paintAlignment(true, true);
222 public void fontChanged()
224 // set idCanvas bufferedImage to null
225 // to prevent drawing old image
226 FontMetrics fm = getFontMetrics(av.getFont());
228 scalePanelHolder.setPreferredSize(
229 new Dimension(10, av.getCharHeight() + fm.getDescent()));
230 idSpaceFillerPanel1.setPreferredSize(
231 new Dimension(10, av.getCharHeight() + fm.getDescent()));
232 idwidthAdjuster.invalidate();
233 scalePanelHolder.invalidate();
234 // BH 2018 getIdPanel().getIdCanvas().gg = null;
235 getSeqPanel().seqCanvas.img = null;
236 getAnnotationPanel().adjustPanelHeight();
238 Dimension d = calculateIdWidth();
240 d.setSize(d.width + 4, d.height);
241 getIdPanel().getIdCanvas().setPreferredSize(d);
242 hscrollFillerPanel.setPreferredSize(d);
248 * Calculate the width of the alignment labels based on the displayed names
249 * and any bounds on label width set in preferences.
251 * @return Dimension giving the maximum width of the alignment label panel
252 * that should be used.
254 public Dimension calculateIdWidth()
256 // calculate sensible default width when no preference is available
258 if (av.getIdWidth() < 0)
260 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
261 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
262 r = calculateIdWidth(maxwidth);
263 av.setIdWidth(r.width);
268 r.width = av.getIdWidth();
275 * Calculate the width of the alignment labels based on the displayed names
276 * and any bounds on label width set in preferences.
279 * -1 or maximum width allowed for IdWidth
280 * @return Dimension giving the maximum width of the alignment label panel
281 * that should be used.
283 public Dimension calculateIdWidth(int maxwidth)
285 Container c = new Container();
287 FontMetrics fm = c.getFontMetrics(
288 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
290 AlignmentI al = av.getAlignment();
295 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
297 SequenceI s = al.getSequenceAt(i);
299 id = s.getDisplayId(av.getShowJVSuffix());
301 if (fm.stringWidth(id) > idWidth)
303 idWidth = fm.stringWidth(id);
309 // Also check annotation label widths
312 if (al.getAlignmentAnnotation() != null)
314 fm = c.getFontMetrics(getAlabels().getFont());
316 while (i < al.getAlignmentAnnotation().length)
318 String label = al.getAlignmentAnnotation()[i].label;
320 if (fm.stringWidth(label) > idWidth)
322 idWidth = fm.stringWidth(label);
329 return new Dimension(
330 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
334 * Highlight the given results on the alignment
337 public void highlightSearchResults(SearchResultsI results)
339 boolean scrolled = scrollToPosition(results, 0, false);
341 boolean fastPaint = !(scrolled && av.getWrapAlignment());
343 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
347 * Scroll the view to show the position of the highlighted region in results
350 * @param searchResults
353 public boolean scrollToPosition(SearchResultsI searchResults)
355 return scrollToPosition(searchResults, 0, false);
359 * Scrolls the view (if necessary) to show the position of the first
360 * highlighted region in results (if any). Answers true if the view was
361 * scrolled, or false if no matched region was found, or it is already
365 * @param verticalOffset
366 * if greater than zero, allows scrolling to a position below the
367 * first displayed sequence
369 * if true, try to centre the search results horizontally in the view
372 protected boolean scrollToPosition(SearchResultsI results,
373 int verticalOffset, boolean centre)
375 int startv, endv, starts, ends;
376 ViewportRanges ranges = av.getRanges();
378 if (results == null || results.isEmpty() || av == null
379 || av.getAlignment() == null)
383 int seqIndex = av.getAlignment().findIndex(results);
388 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
390 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
399 * To centre results, scroll to positions half the visible width
400 * left/right of the start/end positions
404 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
405 start = Math.max(start - offset, 0);
406 end = end + offset - 1;
412 if (end == seq.getEnd())
417 if (av.hasHiddenColumns())
419 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
420 start = hidden.absoluteToVisibleColumn(start);
421 end = hidden.absoluteToVisibleColumn(end);
424 if (!hidden.isVisible(r[0]))
426 // don't scroll - position isn't visible
433 * allow for offset of target sequence (actually scroll to one above it)
435 seqIndex = Math.max(0, seqIndex - verticalOffset);
436 boolean scrollNeeded = true;
438 if (!av.getWrapAlignment())
440 if ((startv = ranges.getStartRes()) >= start)
443 * Scroll left to make start of search results visible
445 setScrollValues(start, seqIndex);
447 else if ((endv = ranges.getEndRes()) <= end)
450 * Scroll right to make end of search results visible
452 setScrollValues(startv + end - endv, seqIndex);
454 else if ((starts = ranges.getStartSeq()) > seqIndex)
457 * Scroll up to make start of search results visible
459 setScrollValues(ranges.getStartRes(), seqIndex);
461 else if ((ends = ranges.getEndSeq()) <= seqIndex)
464 * Scroll down to make end of search results visible
466 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
470 * Else results are already visible - no need to scroll
472 scrollNeeded = false;
476 scrollNeeded = ranges.scrollToWrappedVisible(start);
479 paintAlignment(false, false);
487 * @return DOCUMENT ME!
489 public OverviewPanel getOverviewPanel()
491 return overviewPanel;
500 public void setOverviewPanel(OverviewPanel op)
508 * Hide or show annotation panel
511 public void setAnnotationVisible(boolean b)
513 if (!av.getWrapAlignment())
515 annotationSpaceFillerHolder.setVisible(b);
516 annotationScroller.setVisible(b);
522 * automatically adjust annotation panel height for new annotation whilst
523 * ensuring the alignment is still visible.
526 public void adjustAnnotationHeight()
528 // TODO: display vertical annotation scrollbar if necessary
529 // this is called after loading new annotation onto alignment
530 if (alignFrame.getHeight() == 0)
532 System.out.println("NEEDS FIXING");
534 validateAnnotationDimensions(true);
536 // TODO: many places call this method and also paintAlignment with various
537 // different settings. this means multiple redraws are triggered...
538 paintAlignment(true, av.needToUpdateStructureViews());
542 * calculate the annotation dimensions and refresh slider values accordingly.
543 * need to do repaints/notifys afterwards.
545 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
547 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
548 // are not changing ancestors, and keyboard action listeners do
549 // not need to be reset. addNotify() is a very expensive operation,
550 // requiring a full re-layout of all parents and children.
551 // Note in JComponent:
552 // This method is called by the toolkit internally and should
553 // not be called directly by programs.
554 // I note that addNotify() is called in several areas of Jalview.
556 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
557 annotationHeight = getAnnotationPanel()
558 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
561 annotationScroller.setPreferredSize(
562 new Dimension(annotationScroller.getWidth(), annotationHeight));
564 Dimension e = idPanel.getSize();
565 alabels.setSize(new Dimension(e.width, annotationHeight));
568 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
569 annotationSpaceFillerHolder.getWidth(), annotationHeight));
570 annotationScroller.validate();
571 annotationScroller.addNotify();
575 * update alignment layout for viewport settings
580 public void updateLayout()
583 setAnnotationVisible(av.isShowAnnotation());
584 boolean wrap = av.getWrapAlignment();
585 ViewportRanges ranges = av.getRanges();
586 ranges.setStartSeq(0);
587 scalePanelHolder.setVisible(!wrap);
588 hscroll.setVisible(!wrap);
589 idwidthAdjuster.setVisible(!wrap);
593 annotationScroller.setVisible(false);
594 annotationSpaceFillerHolder.setVisible(false);
596 else if (av.isShowAnnotation())
598 annotationScroller.setVisible(true);
599 annotationSpaceFillerHolder.setVisible(true);
600 validateAnnotationDimensions(false);
603 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
605 { // may not yet be laid out
608 int widthInRes = getSeqPanel().seqCanvas
609 .getWrappedCanvasWidth(canvasWidth);
610 ranges.setViewportWidth(widthInRes);
614 int widthInRes = (canvasWidth / av.getCharWidth());
615 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
616 / av.getCharHeight());
618 ranges.setViewportWidth(widthInRes);
619 ranges.setViewportHeight(heightInSeq);
623 idSpaceFillerPanel1.setVisible(!wrap);
629 * Adjust row/column scrollers to show a visible position in the alignment.
632 * visible column to scroll to
634 * visible row to scroll to
637 public void setScrollValues(int xpos, int ypos)
642 if (av == null || av.getAlignment() == null)
647 if (av.getWrapAlignment())
649 setScrollingForWrappedPanel(x);
653 int width = av.getAlignment().getVisibleWidth();
654 int height = av.getAlignment().getHeight();
656 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
657 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
664 if (vextent > height)
669 if ((hextent + x) > width)
674 if ((vextent + y) > height)
676 y = height - vextent;
689 // update the scroll values
690 hscroll.setValues(x, hextent, 0, width);
691 vscroll.setValues(y, vextent, 0, height);
696 * Respond to adjustment event when horizontal or vertical scrollbar is
700 * adjustment event encoding whether hscroll or vscroll changed
703 public void adjustmentValueChanged(AdjustmentEvent evt)
705 if (av.getWrapAlignment())
707 adjustScrollingWrapped(evt);
711 ViewportRanges ranges = av.getRanges();
713 if (evt.getSource() == hscroll)
715 int oldX = ranges.getStartRes();
716 int oldwidth = ranges.getViewportWidth();
717 int x = hscroll.getValue();
718 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
720 // if we're scrolling to the position we're already at, stop
721 // this prevents infinite recursion of events when the scroll/viewport
722 // ranges values are the same
723 if ((x == oldX) && (width == oldwidth))
727 ranges.setViewportStartAndWidth(x, width);
729 else if (evt.getSource() == vscroll)
731 int oldY = ranges.getStartSeq();
732 int oldheight = ranges.getViewportHeight();
733 int y = vscroll.getValue();
734 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
736 // if we're scrolling to the position we're already at, stop
737 // this prevents infinite recursion of events when the scroll/viewport
738 // ranges values are the same
739 if ((y == oldY) && (height == oldheight))
743 ranges.setViewportStartAndHeight(y, height);
749 * Responds to a scroll change by setting the start position of the viewport.
754 protected void adjustScrollingWrapped(AdjustmentEvent evt)
756 if (evt.getSource() == hscroll)
758 return; // no horizontal scroll when wrapped
760 final ViewportRanges ranges = av.getRanges();
762 if (evt.getSource() == vscroll)
764 int newY = vscroll.getValue();
767 * if we're scrolling to the position we're already at, stop
768 * this prevents infinite recursion of events when the scroll/viewport
769 * ranges values are the same
771 int oldX = ranges.getStartRes();
772 int oldY = ranges.getWrappedScrollPosition(oldX);
780 * limit page up/down to one width's worth of positions
782 int rowSize = ranges.getViewportWidth();
783 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
784 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
789 // This is only called if file loaded is a jar file that
790 // was wrapped when saved and user has wrap alignment true
791 // as preference setting
792 SwingUtilities.invokeLater(new Runnable()
797 // When updating scrolling to use ViewportChange events, this code
798 // could not be validated and it is not clear if it is now being
799 // called. Log warning here in case it is called and unforeseen
802 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
804 // scroll to start of panel
805 ranges.setStartRes(0);
806 ranges.setStartSeq(0);
814 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
817 public void paintAlignment(boolean updateOverview,
818 boolean updateStructures)
820 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
821 av.isShowAutocalculatedAbove());
822 sorter.sort(getAlignment().getAlignmentAnnotation(),
823 av.getSortAnnotationsBy());
826 if (updateStructures)
828 av.getStructureSelectionManager().sequenceColoursChanged(this);
833 if (overviewPanel != null)
835 overviewPanel.updateOverviewImage();
847 public void paintComponent(Graphics g)
849 invalidate(); // needed so that the id width adjuster works correctly
851 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
852 idPanelHolder.setPreferredSize(d);
853 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
855 validate(); // needed so that the id width adjuster works correctly
858 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
859 * though I still think this call should be elsewhere.
861 ViewportRanges ranges = av.getRanges();
862 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
863 super.paintComponent(g);
867 * Set vertical scroll bar position, and number of increments, for wrapped
870 * @param topLeftColumn
871 * the column position at top left (0..)
873 private void setScrollingForWrappedPanel(int topLeftColumn)
875 ViewportRanges ranges = av.getRanges();
876 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
877 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
880 * a scrollbar's value can be set to at most (maximum-extent)
881 * so we add extent (1) to the maxScroll value
883 vscroll.setUnitIncrement(1);
884 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
897 * @return DOCUMENT ME!
899 * @throws PrinterException
903 public int print(Graphics pg, PageFormat pf, int pi)
904 throws PrinterException
906 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
908 int pwidth = (int) pf.getImageableWidth();
909 int pheight = (int) pf.getImageableHeight();
911 if (av.getWrapAlignment())
913 return printWrappedAlignment(pwidth, pheight, pi, pg);
917 return printUnwrapped(pwidth, pheight, pi, pg, pg);
922 * Draws the alignment image, including sequence ids, sequences, and
923 * annotation labels and annotations if shown, on either one or two Graphics
933 * the graphics context for sequence ids and annotation labels
934 * @param alignmentGraphics
935 * the graphics context for sequences and annotations (may or may not
936 * be the same context as idGraphics)
938 * @throws PrinterException
940 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
941 Graphics idGraphics, Graphics alignmentGraphics)
942 throws PrinterException
944 final int idWidth = getVisibleIdWidth(false);
947 * Get the horizontal offset to where we draw the sequences.
948 * This is idWidth if using a single Graphics context, else zero.
950 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
953 FontMetrics fm = getFontMetrics(av.getFont());
954 final int charHeight = av.getCharHeight();
955 final int scaleHeight = charHeight + fm.getDescent();
957 idGraphics.setColor(Color.white);
958 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
959 idGraphics.setFont(av.getFont());
962 * How many sequences and residues can we fit on a printable page?
964 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
966 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
968 final int alignmentWidth = av.getAlignment().getVisibleWidth();
969 int pagesWide = (alignmentWidth / totalRes) + 1;
971 final int startRes = (pageIndex % pagesWide) * totalRes;
972 final int endRes = Math.min(startRes + totalRes - 1,
975 final int startSeq = (pageIndex / pagesWide) * totalSeq;
976 final int alignmentHeight = av.getAlignment().getHeight();
977 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
979 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
981 if (av.isShowAnnotation())
983 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
986 pagesHigh /= pageHeight;
988 if (pageIndex >= (pagesWide * pagesHigh))
990 return Printable.NO_SUCH_PAGE;
992 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
995 * draw the Scale at horizontal offset, then reset to top left (0, 0)
997 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
998 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
999 pageWidth - idWidth, scaleHeight);
1000 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1003 * Draw the sequence ids, offset for scale height,
1004 * then reset to top left (0, 0)
1006 idGraphics.translate(0, scaleHeight);
1007 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1008 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1009 : av.getSelectionGroup().getSequences(null);
1010 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1013 idGraphics.setFont(av.getFont());
1014 idGraphics.translate(0, -scaleHeight);
1017 * draw the sequences, offset for scale height, and id width (if using a
1018 * single graphics context), then reset to (0, scale height)
1020 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1021 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1022 endRes, startSeq, endSeq - 1);
1023 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1025 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1028 * draw annotation labels; drawComponent() translates by
1029 * getScrollOffset(), so compensate for that first;
1030 * then reset to (0, scale height)
1032 int offset = getAlabels().getScrollOffset();
1033 idGraphics.translate(0, -offset);
1034 idGraphics.translate(0, alignmentDrawnHeight);
1035 getAlabels().drawComponent(idGraphics, idWidth);
1036 idGraphics.translate(0, -alignmentDrawnHeight);
1039 * draw the annotations starting at
1040 * (idOffset, alignmentHeight) from (0, scaleHeight)
1042 alignmentGraphics.translate(alignmentGraphicsOffset,
1043 alignmentDrawnHeight);
1044 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1045 alignmentGraphics, -1, startRes, endRes + 1);
1048 return Printable.PAGE_EXISTS;
1052 * Prints one page of an alignment in wrapped mode. Returns
1053 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1054 * no page could be drawn (page number out of range).
1064 * @throws PrinterException
1066 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1067 Graphics g) throws PrinterException
1069 int annotationHeight = 0;
1070 if (av.isShowAnnotation())
1072 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1075 int hgap = av.getCharHeight();
1076 if (av.getScaleAboveWrapped())
1078 hgap += av.getCharHeight();
1081 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1084 int idWidth = getVisibleIdWidth(false);
1086 int maxwidth = av.getAlignment().getVisibleWidth();
1088 int resWidth = getSeqPanel().seqCanvas
1089 .getWrappedCanvasWidth(pageWidth - idWidth);
1091 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1093 g.setColor(Color.white);
1094 g.fillRect(0, 0, pageWidth, pageHeight);
1095 g.setFont(av.getFont());
1096 g.setColor(Color.black);
1099 * method: print the whole wrapped alignment, but with a clip region that
1100 * is restricted to the requested page; this supports selective print of
1101 * single pages or ranges, (at the cost of some repeated processing in
1102 * the 'normal' case, when all pages are printed)
1104 g.translate(0, -pageNumber * pageHeight);
1106 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1109 * draw sequence ids and annotation labels (if shown)
1111 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1112 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1114 g.translate(idWidth, 0);
1116 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1119 if ((pageNumber * pageHeight) < totalHeight)
1121 return Printable.PAGE_EXISTS;
1125 return Printable.NO_SUCH_PAGE;
1130 * get current sequence ID panel width, or nominal value if panel were to be
1131 * displayed using default settings
1135 public int getVisibleIdWidth()
1137 return getVisibleIdWidth(true);
1141 * get current sequence ID panel width, or nominal value if panel were to be
1142 * displayed using default settings
1145 * indicate if the Id width for onscreen or offscreen display should
1149 public int getVisibleIdWidth(boolean onscreen)
1151 // see if rendering offscreen - check preferences and calc width accordingly
1152 if (!onscreen && Cache.getDefault(Preferences.FIGURE_AUTOIDWIDTH, false))
1154 return calculateIdWidth(-1).width + 4;
1156 Integer idwidth = null;
1157 if (onscreen || (idwidth = Cache
1158 .getIntegerProperty(Preferences.FIGURE_FIXEDIDWIDTH)) == null)
1160 int w = getIdPanel().getWidth();
1161 return (w > 0 ? w : calculateIdWidth().width + 4);
1163 return idwidth.intValue() + 4;
1167 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1168 * writes it to the specified file
1173 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1175 final int borderBottomOffset = 5;
1177 AlignmentDimension aDimension = getAlignmentDimension();
1178 // todo use a lambda function in place of callback here?
1179 ImageWriterI writer = new ImageWriterI()
1182 public void exportImage(Graphics graphics) throws Exception
1184 if (av.getWrapAlignment())
1186 printWrappedAlignment(aDimension.getWidth(),
1187 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1191 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1192 graphics, graphics);
1197 String fileTitle = alignFrame.getTitle();
1198 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1200 int imageWidth = aDimension.getWidth();
1201 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1202 String of = MessageManager.getString("label.alignment");
1203 exporter.doExport(file, this, imageWidth, imageHeight, of);
1207 * Calculates and returns a suitable width and height (in pixels) for an
1212 public AlignmentDimension getAlignmentDimension()
1214 int maxwidth = av.getAlignment().getVisibleWidth();
1216 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1217 + getScalePanel().getHeight();
1218 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1220 if (av.getWrapAlignment())
1222 height = getWrappedHeight();
1223 if (Jalview.isHeadlessMode())
1225 // need to obtain default alignment width and then add in any
1226 // additional allowance for id margin
1227 // this duplicates the calculation in getWrappedHeight but adjusts for
1229 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1230 - alignFrame.getInsets().left - alignFrame.getInsets().right
1231 - getVisibleIdWidth() + getVisibleIdWidth(false);
1235 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1239 else if (av.isShowAnnotation())
1241 height += getAnnotationPanel().adjustPanelHeight() + 3;
1243 return new AlignmentDimension(width, height);
1247 public void makePNGImageMap(File imgMapFile, String imageName)
1249 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1250 // ////////////////////////////////////////////
1251 int idWidth = getVisibleIdWidth(false);
1252 FontMetrics fm = getFontMetrics(av.getFont());
1253 int scaleHeight = av.getCharHeight() + fm.getDescent();
1256 // ////////////////////////////////
1257 if (imgMapFile != null)
1261 int sSize = av.getAlignment().getHeight();
1262 int alwidth = av.getAlignment().getWidth();
1263 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1264 out.println(HTMLOutput.getImageMapHTML());
1265 out.println("<img src=\"" + imageName
1266 + "\" border=\"0\" usemap=\"#Map\" >"
1267 + "<map name=\"Map\">");
1269 for (int s = 0; s < sSize; s++)
1271 int sy = s * av.getCharHeight() + scaleHeight;
1273 SequenceI seq = av.getAlignment().getSequenceAt(s);
1274 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1275 for (int column = 0; column < alwidth; column++)
1277 StringBuilder text = new StringBuilder(512);
1278 String triplet = null;
1279 if (av.getAlignment().isNucleotide())
1281 triplet = ResidueProperties.nucleotideName.get(seq
1282 .getCharAt(column) + "");
1286 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1290 if (triplet == null)
1295 int seqPos = seq.findPosition(column);
1296 int gSize = groups.length;
1297 for (int g = 0; g < gSize; g++)
1299 if (text.length() < 1)
1301 text.append("<area shape=\"rect\" coords=\"")
1302 .append((idWidth + column * av.getCharWidth()))
1303 .append(",").append(sy).append(",")
1304 .append((idWidth + (column + 1) * av.getCharWidth()))
1305 .append(",").append((av.getCharHeight() + sy))
1306 .append("\"").append(" onMouseOver=\"toolTip('")
1307 .append(seqPos).append(" ").append(triplet);
1310 if (groups[g].getStartRes() < column
1311 && groups[g].getEndRes() > column)
1313 text.append("<br><em>").append(groups[g].getName())
1318 if (text.length() < 1)
1320 text.append("<area shape=\"rect\" coords=\"")
1321 .append((idWidth + column * av.getCharWidth()))
1322 .append(",").append(sy).append(",")
1323 .append((idWidth + (column + 1) * av.getCharWidth()))
1324 .append(",").append((av.getCharHeight() + sy))
1325 .append("\"").append(" onMouseOver=\"toolTip('")
1326 .append(seqPos).append(" ").append(triplet);
1328 if (!Comparison.isGap(seq.getCharAt(column)))
1330 List<SequenceFeature> features = seq.findFeatures(column, column);
1331 for (SequenceFeature sf : features)
1333 if (sf.isContactFeature())
1335 text.append("<br>").append(sf.getType()).append(" ")
1336 .append(sf.getBegin()).append(":")
1337 .append(sf.getEnd());
1341 text.append("<br>");
1342 text.append(sf.getType());
1343 String description = sf.getDescription();
1344 if (description != null
1345 && !sf.getType().equals(description))
1347 description = description.replace("\"", """);
1348 text.append(" ").append(description);
1351 String status = sf.getStatus();
1352 if (status != null && !"".equals(status))
1354 text.append(" (").append(status).append(")");
1357 if (text.length() > 1)
1359 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1360 out.println(text.toString());
1365 out.println("</map></body></html>");
1368 } catch (Exception ex)
1370 ex.printStackTrace();
1372 } // /////////END OF IMAGE MAP
1376 int getWrappedHeight()
1378 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1380 if (Jalview.isHeadlessMode())
1382 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1383 - vscroll.getPreferredSize().width
1384 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1387 int chunkWidth = getSeqPanel().seqCanvas
1388 .getWrappedCanvasWidth(seqPanelWidth);
1390 int hgap = av.getCharHeight();
1391 if (av.getScaleAboveWrapped())
1393 hgap += av.getCharHeight();
1396 int annotationHeight = 0;
1397 if (av.isShowAnnotation())
1399 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1402 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1405 int maxwidth = av.getAlignment().getWidth();
1406 if (av.hasHiddenColumns())
1408 maxwidth = av.getAlignment().getHiddenColumns()
1409 .absoluteToVisibleColumn(maxwidth) - 1;
1412 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1418 * close the panel - deregisters all listeners and nulls any references to
1421 public void closePanel()
1423 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1424 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1425 PaintRefresher.RemoveComponent(this);
1430 * try to ensure references are nulled
1432 if (annotationPanel != null)
1434 annotationPanel.dispose();
1435 annotationPanel = null;
1440 av.removePropertyChangeListener(propertyChangeListener);
1441 propertyChangeListener = null;
1442 StructureSelectionManager ssm = av.getStructureSelectionManager();
1443 ssm.removeStructureViewerListener(getSeqPanel(), null);
1444 ssm.removeSelectionListener(getSeqPanel());
1445 ssm.removeCommandListener(av);
1446 ssm.removeStructureViewerListener(getSeqPanel(), null);
1447 ssm.removeSelectionListener(getSeqPanel());
1453 if (Cache.log.isDebugEnabled())
1455 Cache.log.warn("Closing alignment panel which is already closed.");
1461 * Close any open dialogs that would be orphaned when this one is closed
1463 protected void closeChildFrames()
1465 if (overviewPanel != null)
1467 overviewPanel.dispose();
1468 overviewPanel = null;
1470 if (calculationDialog != null)
1472 calculationDialog.closeFrame();
1473 calculationDialog = null;
1478 * hides or shows dynamic annotation rows based on groups and av state flags
1480 public void updateAnnotation()
1482 updateAnnotation(false, false);
1485 public void updateAnnotation(boolean applyGlobalSettings)
1487 updateAnnotation(applyGlobalSettings, false);
1490 public void updateAnnotation(boolean applyGlobalSettings,
1491 boolean preserveNewGroupSettings)
1493 av.updateGroupAnnotationSettings(applyGlobalSettings,
1494 preserveNewGroupSettings);
1495 adjustAnnotationHeight();
1499 public AlignmentI getAlignment()
1501 return av == null ? null : av.getAlignment();
1505 public String getViewName()
1507 return av.getViewName();
1511 * Make/Unmake this alignment panel the current input focus
1515 public void setSelected(boolean b)
1519 if (alignFrame.getSplitViewContainer() != null)
1522 * bring enclosing SplitFrame to front first if there is one
1524 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1526 alignFrame.setSelected(b);
1527 } catch (Exception ex)
1533 alignFrame.setDisplayedView(this);
1538 public StructureSelectionManager getStructureSelectionManager()
1540 return av.getStructureSelectionManager();
1544 public void raiseOOMWarning(String string, OutOfMemoryError error)
1546 new OOMWarning(string, error, this);
1550 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1553 return new FeatureRenderer(this);
1557 public jalview.api.FeatureRenderer getFeatureRenderer()
1559 return seqPanel.seqCanvas.getFeatureRenderer();
1562 public void updateFeatureRenderer(
1563 jalview.renderer.seqfeatures.FeatureRenderer fr)
1565 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1568 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1570 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1572 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1576 public ScalePanel getScalePanel()
1581 public void setScalePanel(ScalePanel scalePanel)
1583 this.scalePanel = scalePanel;
1586 public SeqPanel getSeqPanel()
1591 public void setSeqPanel(SeqPanel seqPanel)
1593 this.seqPanel = seqPanel;
1596 public AnnotationPanel getAnnotationPanel()
1598 return annotationPanel;
1601 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1603 this.annotationPanel = annotationPanel;
1606 public AnnotationLabels getAlabels()
1611 public void setAlabels(AnnotationLabels alabels)
1613 this.alabels = alabels;
1616 public IdPanel getIdPanel()
1621 public void setIdPanel(IdPanel idPanel)
1623 this.idPanel = idPanel;
1627 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1628 * The aim is to keep the two alignments 'lined up' on their centre columns.
1631 * holds mapped region(s) of this alignment that we are scrolling
1632 * 'to'; may be modified for sequence offset by this method
1633 * @param verticalOffset
1634 * the number of visible sequences to show above the mapped region
1636 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1638 scrollToPosition(sr, verticalOffset, true);
1642 * Set a flag to say do not scroll any (cDNA/protein) complement.
1646 protected void setToScrollComplementPanel(boolean b)
1648 this.scrollComplementaryPanel = b;
1652 * Get whether to scroll complement panel
1654 * @return true if cDNA/protein complement panels should be scrolled
1656 protected boolean isSetToScrollComplementPanel()
1658 return this.scrollComplementaryPanel;
1664 * @adjustHeight if true, try to recalculate panel height for visible
1667 protected void refresh(boolean adjustHeight)
1669 validateAnnotationDimensions(adjustHeight);
1673 // sort, repaint, update overview
1674 paintAlignment(true, false);
1678 // lightweight repaint
1685 * Property change event fired when a change is made to the viewport ranges
1686 * object associated with this alignment panel's viewport
1688 public void propertyChange(PropertyChangeEvent evt)
1690 // update this panel's scroll values based on the new viewport ranges values
1691 ViewportRanges ranges = av.getRanges();
1692 int x = ranges.getStartRes();
1693 int y = ranges.getStartSeq();
1694 setScrollValues(x, y);
1696 // now update any complementary alignment (its viewport ranges object
1697 // is different so does not get automatically updated)
1698 if (isSetToScrollComplementPanel())
1700 setToScrollComplementPanel(false);
1701 av.scrollComplementaryAlignment();
1702 setToScrollComplementPanel(true);
1707 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1708 * reference should be nulled when the dialog is closed.
1710 * @param calculationChooser
1712 public void setCalculationDialog(CalculationChooser calculationChooser)
1714 calculationDialog = calculationChooser;
1718 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1721 public CalculationChooser getCalculationDialog()
1723 return calculationDialog;
1727 public SequenceRenderer getSequenceRenderer()
1729 return seqPanel.seqCanvas.getSequenceRenderer();