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.api.AlignViewportI;
24 import jalview.bin.Cache;
25 import jalview.commands.EditCommand;
26 import jalview.commands.EditCommand.Action;
27 import jalview.commands.EditCommand.Edit;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.ColumnSelection;
30 import jalview.datamodel.HiddenColumns;
31 import jalview.datamodel.SearchResultMatchI;
32 import jalview.datamodel.SearchResults;
33 import jalview.datamodel.SearchResultsI;
34 import jalview.datamodel.Sequence;
35 import jalview.datamodel.SequenceFeature;
36 import jalview.datamodel.SequenceGroup;
37 import jalview.datamodel.SequenceI;
38 import jalview.io.SequenceAnnotationReport;
39 import jalview.renderer.ResidueShaderI;
40 import jalview.schemes.ResidueProperties;
41 import jalview.structure.SelectionListener;
42 import jalview.structure.SelectionSource;
43 import jalview.structure.SequenceListener;
44 import jalview.structure.StructureSelectionManager;
45 import jalview.structure.VamsasSource;
46 import jalview.util.Comparison;
47 import jalview.util.MappingUtils;
48 import jalview.util.MessageManager;
49 import jalview.util.Platform;
50 import jalview.viewmodel.AlignmentViewport;
52 import java.awt.BorderLayout;
53 import java.awt.Color;
55 import java.awt.FontMetrics;
56 import java.awt.Point;
57 import java.awt.event.MouseEvent;
58 import java.awt.event.MouseListener;
59 import java.awt.event.MouseMotionListener;
60 import java.awt.event.MouseWheelEvent;
61 import java.awt.event.MouseWheelListener;
62 import java.util.ArrayList;
63 import java.util.Collections;
64 import java.util.List;
65 import java.util.ListIterator;
67 import javax.swing.JPanel;
68 import javax.swing.SwingUtilities;
69 import javax.swing.ToolTipManager;
75 * @version $Revision: 1.130 $
77 public class SeqPanel extends JPanel implements MouseListener,
78 MouseMotionListener, MouseWheelListener, SequenceListener,
83 public SeqCanvas seqCanvas;
86 public AlignmentPanel ap;
88 protected int lastres;
90 protected int startseq;
92 protected AlignViewport av;
94 ScrollThread scrollThread = null;
96 boolean mouseDragging = false;
98 boolean editingSeqs = false;
100 boolean groupEditing = false;
102 // ////////////////////////////////////////
103 // ///Everything below this is for defining the boundary of the rubberband
104 // ////////////////////////////////////////
107 boolean changeEndSeq = false;
109 boolean changeStartSeq = false;
111 boolean changeEndRes = false;
113 boolean changeStartRes = false;
115 SequenceGroup stretchGroup = null;
117 boolean remove = false;
119 Point lastMousePress;
121 boolean mouseWheelPressed = false;
123 StringBuffer keyboardNo1;
125 StringBuffer keyboardNo2;
127 java.net.URL linkImageURL;
129 private final SequenceAnnotationReport seqARep;
131 StringBuilder tooltipText = new StringBuilder();
135 EditCommand editCommand;
137 StructureSelectionManager ssm;
139 SearchResultsI lastSearchResults;
142 * Creates a new SeqPanel object.
149 public SeqPanel(AlignViewport av, AlignmentPanel ap)
151 linkImageURL = getClass().getResource("/images/link.gif");
152 seqARep = new SequenceAnnotationReport(linkImageURL.toString());
153 ToolTipManager.sharedInstance().registerComponent(this);
154 ToolTipManager.sharedInstance().setInitialDelay(0);
155 ToolTipManager.sharedInstance().setDismissDelay(10000);
157 setBackground(Color.white);
159 seqCanvas = new SeqCanvas(ap);
160 setLayout(new BorderLayout());
161 add(seqCanvas, BorderLayout.CENTER);
167 addMouseMotionListener(this);
168 addMouseListener(this);
169 addMouseWheelListener(this);
170 ssm = av.getStructureSelectionManager();
171 ssm.addStructureViewerListener(this);
172 ssm.addSelectionListener(this);
176 int startWrapBlock = -1;
178 int wrappedBlock = -1;
181 * Returns the aligned sequence position (base 0) at the mouse position, or
182 * the closest visible one
187 int findColumn(MouseEvent evt)
192 if (av.getWrapAlignment())
195 int hgap = av.getCharHeight();
196 if (av.getScaleAboveWrapped())
198 hgap += av.getCharHeight();
201 int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
202 + hgap + seqCanvas.getAnnotationHeight();
206 x -= seqCanvas.LABEL_WEST;
208 int cwidth = seqCanvas.getWrappedCanvasWidth(this.getWidth());
214 wrappedBlock = y / cHeight;
215 wrappedBlock += av.getRanges().getStartRes() / cwidth;
217 res = wrappedBlock * cwidth + x / av.getCharWidth();
222 if (x > seqCanvas.getX() + seqCanvas.getWidth())
224 // make sure we calculate relative to visible alignment, rather than
226 x = seqCanvas.getX() + seqCanvas.getWidth();
228 res = (x / av.getCharWidth()) + av.getRanges().getStartRes();
229 if (res > av.getRanges().getEndRes())
232 res = av.getRanges().getEndRes();
236 if (av.hasHiddenColumns())
238 res = av.getAlignment().getHiddenColumns()
239 .adjustForHiddenColumns(res);
246 int findSeq(MouseEvent evt)
251 if (av.getWrapAlignment())
253 int hgap = av.getCharHeight();
254 if (av.getScaleAboveWrapped())
256 hgap += av.getCharHeight();
259 int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
260 + hgap + seqCanvas.getAnnotationHeight();
264 seq = Math.min((y % cHeight) / av.getCharHeight(), av.getAlignment()
269 seq = Math.min((y / av.getCharHeight())
270 + av.getRanges().getStartSeq(),
272 .getAlignment().getHeight() - 1);
279 * When all of a sequence of edits are complete, put the resulting edit list
280 * on the history stack (undo list), and reset flags for editing in progress.
286 if (editCommand != null && editCommand.getSize() > 0)
288 ap.alignFrame.addHistoryItem(editCommand);
289 av.firePropertyChange("alignment", null, av.getAlignment()
295 * Tidy up come what may...
300 groupEditing = false;
309 seqCanvas.cursorY = getKeyboardNo1() - 1;
313 void setCursorColumn()
315 seqCanvas.cursorX = getKeyboardNo1() - 1;
319 void setCursorRowAndColumn()
321 if (keyboardNo2 == null)
323 keyboardNo2 = new StringBuffer();
327 seqCanvas.cursorX = getKeyboardNo1() - 1;
328 seqCanvas.cursorY = getKeyboardNo2() - 1;
333 void setCursorPosition()
335 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
337 seqCanvas.cursorX = sequence.findIndex(getKeyboardNo1()) - 1;
341 void moveCursor(int dx, int dy)
343 seqCanvas.cursorX += dx;
344 seqCanvas.cursorY += dy;
346 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
348 if (av.hasHiddenColumns()
349 && !hidden.isVisible(seqCanvas.cursorX))
351 int original = seqCanvas.cursorX - dx;
352 int maxWidth = av.getAlignment().getWidth();
354 while (!hidden.isVisible(seqCanvas.cursorX)
355 && seqCanvas.cursorX < maxWidth && seqCanvas.cursorX > 0)
357 seqCanvas.cursorX += dx;
360 if (seqCanvas.cursorX >= maxWidth
361 || !hidden.isVisible(seqCanvas.cursorX))
363 seqCanvas.cursorX = original;
370 void scrollToVisible()
372 if (seqCanvas.cursorX < 0)
374 seqCanvas.cursorX = 0;
376 else if (seqCanvas.cursorX > av.getAlignment().getWidth() - 1)
378 seqCanvas.cursorX = av.getAlignment().getWidth() - 1;
381 if (seqCanvas.cursorY < 0)
383 seqCanvas.cursorY = 0;
385 else if (seqCanvas.cursorY > av.getAlignment().getHeight() - 1)
387 seqCanvas.cursorY = av.getAlignment().getHeight() - 1;
391 if (av.getWrapAlignment())
393 av.getRanges().scrollToWrappedVisible(seqCanvas.cursorX);
397 av.getRanges().scrollToVisible(seqCanvas.cursorX, seqCanvas.cursorY);
399 setStatusMessage(av.getAlignment().getSequenceAt(seqCanvas.cursorY),
400 seqCanvas.cursorX, seqCanvas.cursorY);
405 void setSelectionAreaAtCursor(boolean topLeft)
407 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
409 if (av.getSelectionGroup() != null)
411 SequenceGroup sg = av.getSelectionGroup();
412 // Find the top and bottom of this group
413 int min = av.getAlignment().getHeight(), max = 0;
414 for (int i = 0; i < sg.getSize(); i++)
416 int index = av.getAlignment().findIndex(sg.getSequenceAt(i));
431 sg.setStartRes(seqCanvas.cursorX);
432 if (sg.getEndRes() < seqCanvas.cursorX)
434 sg.setEndRes(seqCanvas.cursorX);
437 min = seqCanvas.cursorY;
441 sg.setEndRes(seqCanvas.cursorX);
442 if (sg.getStartRes() > seqCanvas.cursorX)
444 sg.setStartRes(seqCanvas.cursorX);
447 max = seqCanvas.cursorY + 1;
452 // Only the user can do this
453 av.setSelectionGroup(null);
457 // Now add any sequences between min and max
458 sg.getSequences(null).clear();
459 for (int i = min; i < max; i++)
461 sg.addSequence(av.getAlignment().getSequenceAt(i), false);
466 if (av.getSelectionGroup() == null)
468 SequenceGroup sg = new SequenceGroup();
469 sg.setStartRes(seqCanvas.cursorX);
470 sg.setEndRes(seqCanvas.cursorX);
471 sg.addSequence(sequence, false);
472 av.setSelectionGroup(sg);
475 ap.paintAlignment(false);
479 void insertGapAtCursor(boolean group)
481 groupEditing = group;
482 startseq = seqCanvas.cursorY;
483 lastres = seqCanvas.cursorX;
484 editSequence(true, false, seqCanvas.cursorX + getKeyboardNo1());
488 void deleteGapAtCursor(boolean group)
490 groupEditing = group;
491 startseq = seqCanvas.cursorY;
492 lastres = seqCanvas.cursorX + getKeyboardNo1();
493 editSequence(false, false, seqCanvas.cursorX);
497 void insertNucAtCursor(boolean group, String nuc)
499 // TODO not called - delete?
500 groupEditing = group;
501 startseq = seqCanvas.cursorY;
502 lastres = seqCanvas.cursorX;
503 editSequence(false, true, seqCanvas.cursorX + getKeyboardNo1());
507 void numberPressed(char value)
509 if (keyboardNo1 == null)
511 keyboardNo1 = new StringBuffer();
514 if (keyboardNo2 != null)
516 keyboardNo2.append(value);
520 keyboardNo1.append(value);
528 if (keyboardNo1 != null)
530 int value = Integer.parseInt(keyboardNo1.toString());
534 } catch (Exception x)
545 if (keyboardNo2 != null)
547 int value = Integer.parseInt(keyboardNo2.toString());
551 } catch (Exception x)
565 public void mouseReleased(MouseEvent evt)
567 boolean didDrag = mouseDragging; // did we come here after a drag
568 mouseDragging = false;
569 mouseWheelPressed = false;
571 if (evt.isPopupTrigger()) // Windows: mouseReleased
580 doMouseReleasedDefineMode(evt, didDrag);
594 public void mousePressed(MouseEvent evt)
596 lastMousePress = evt.getPoint();
598 if (SwingUtilities.isMiddleMouseButton(evt))
600 mouseWheelPressed = true;
604 boolean isControlDown = Platform.isControlDown(evt);
605 if (evt.isShiftDown() || isControlDown)
615 doMousePressedDefineMode(evt);
619 int seq = findSeq(evt);
620 int res = findColumn(evt);
622 if (seq < 0 || res < 0)
627 if ((seq < av.getAlignment().getHeight())
628 && (res < av.getAlignment().getSequenceAt(seq).getLength()))
645 public void mouseOverSequence(SequenceI sequence, int index, int pos)
647 String tmp = sequence.hashCode() + " " + index + " " + pos;
649 if (lastMessage == null || !lastMessage.equals(tmp))
651 // System.err.println("mouseOver Sequence: "+tmp);
652 ssm.mouseOverSequence(sequence, index, pos, av);
658 * Highlight the mapped region described by the search results object (unless
659 * unchanged). This supports highlight of protein while mousing over linked
660 * cDNA and vice versa. The status bar is also updated to show the location of
661 * the start of the highlighted region.
664 public void highlightSequence(SearchResultsI results)
666 if (results == null || results.equals(lastSearchResults))
670 lastSearchResults = results;
672 if (av.isFollowHighlight())
674 // don't allow highlight of protein/cDNA to also scroll a complementary
675 // panel,as this sets up a feedback loop (scrolling panel 1 causes moused
676 // over residue to change abruptly, causing highlighted residue in panel 2
677 // to change, causing a scroll in panel 1 etc)
678 ap.setToScrollComplementPanel(false);
679 if (ap.scrollToPosition(results, false))
681 seqCanvas.revalidate();
683 ap.setToScrollComplementPanel(true);
685 setStatusMessage(results);
686 seqCanvas.highlightSearchResults(results);
690 public VamsasSource getVamsasSource()
692 return this.ap == null ? null : this.ap.av;
696 public void updateColours(SequenceI seq, int index)
698 System.out.println("update the seqPanel colours");
709 public void mouseMoved(MouseEvent evt)
713 // This is because MacOSX creates a mouseMoved
714 // If control is down, other platforms will not.
718 final int column = findColumn(evt);
719 int seq = findSeq(evt);
720 if (column < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
725 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
727 if (column >= sequence.getLength())
733 * set status bar message, returning residue position in sequence
735 boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
736 final int pos = setStatusMessage(sequence, column, seq);
737 if (ssm != null && !isGapped)
739 mouseOverSequence(sequence, column, pos);
742 tooltipText.setLength(6); // Cuts the buffer back to <html>
744 SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
747 for (int g = 0; g < groups.length; g++)
749 if (groups[g].getStartRes() <= column
750 && groups[g].getEndRes() >= column)
752 if (!groups[g].getName().startsWith("JTreeGroup")
753 && !groups[g].getName().startsWith("JGroup"))
755 tooltipText.append(groups[g].getName());
758 if (groups[g].getDescription() != null)
760 tooltipText.append(": " + groups[g].getDescription());
767 * add any features at the position to the tooltip; if over a gap, only
768 * add features that straddle the gap (pos may be the residue before or
771 if (av.isShowSequenceFeatures())
773 List<SequenceFeature> features = ap.getFeatureRenderer()
774 .findFeaturesAtRes(sequence.getDatasetSequence(), pos);
777 removeAdjacentFeatures(features, column + 1, sequence);
779 seqARep.appendFeatures(tooltipText, pos, features,
780 this.ap.getSeqPanel().seqCanvas.fr.getMinMax());
782 if (tooltipText.length() == 6) // <html>
784 setToolTipText(null);
789 if (lastTooltip == null
790 || !lastTooltip.equals(tooltipText.toString()))
792 String formatedTooltipText = JvSwingUtils.wrapTooltip(true,
793 tooltipText.toString());
794 // String formatedTooltipText = tooltipText.toString();
795 setToolTipText(formatedTooltipText);
796 lastTooltip = tooltipText.toString();
804 * Removes from the list of features any that start after, or end before, the
805 * given column position. This allows us to retain only those features
806 * adjacent to a gapped position that straddle the position. Contact features
807 * that 'straddle' the position are also removed, since they are not 'at' the
812 * alignment column (1..)
815 protected void removeAdjacentFeatures(List<SequenceFeature> features,
816 final int column, SequenceI sequence)
818 // TODO should this be an AlignViewController method (and reused by applet)?
819 ListIterator<SequenceFeature> it = features.listIterator();
822 SequenceFeature sf = it.next();
823 if (sf.isContactFeature()
824 || sequence.findIndex(sf.getBegin()) > column
825 || sequence.findIndex(sf.getEnd()) < column)
832 private Point lastp = null;
837 * @see javax.swing.JComponent#getToolTipLocation(java.awt.event.MouseEvent)
840 public Point getToolTipLocation(MouseEvent event)
842 int x = event.getX(), w = getWidth();
843 int wdth = (w - x < 200) ? -(w / 2) : 5; // switch sides when tooltip is too
846 if (!event.isShiftDown() || p == null)
848 p = (tooltipText != null && tooltipText.length() > 6) ? new Point(
849 event.getX() + wdth, event.getY() - 20) : null;
852 * TODO: try to modify position region is not obcured by tooltip
860 * set when the current UI interaction has resulted in a change that requires
861 * overview shading to be recalculated. this could be changed to something
862 * more expressive that indicates what actually has changed, so selective
863 * redraws can be applied
865 private boolean needOverviewUpdate = false; // TODO: refactor to avcontroller
868 * set if av.getSelectionGroup() refers to a group that is defined on the
869 * alignment view, rather than a transient selection
871 // private boolean editingDefinedGroup = false; // TODO: refactor to
872 // avcontroller or viewModel
875 * Sets the status message in alignment panel, showing the sequence number
876 * (index) and id, and residue and residue position if not at a gap, for the
877 * given sequence and column position. Returns the residue position returned
878 * by Sequence.findPosition. Note this may be for the nearest adjacent residue
879 * if at a gapped position.
882 * aligned sequence object
886 * index of sequence in alignment
887 * @return sequence position of residue at column, or adjacent residue if at a
890 int setStatusMessage(SequenceI sequence, final int column, int seq)
892 StringBuilder text = new StringBuilder(32);
895 * Sequence number (if known), and sequence name.
897 String seqno = seq == -1 ? "" : " " + (seq + 1);
898 text.append("Sequence").append(seqno).append(" ID: ")
899 .append(sequence.getName());
901 String residue = null;
904 * Try to translate the display character to residue name (null for gap).
906 final String displayChar = String.valueOf(sequence.getCharAt(column));
907 boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
908 int pos = sequence.findPosition(column);
912 boolean nucleotide = av.getAlignment().isNucleotide();
915 residue = ResidueProperties.nucleotideName.get(displayChar);
919 residue = "X".equalsIgnoreCase(displayChar) ? "X" : ("*"
920 .equals(displayChar) ? "STOP"
921 : ResidueProperties.aa2Triplet.get(displayChar));
923 text.append(" ").append(nucleotide ? "Nucleotide" : "Residue")
924 .append(": ").append(residue == null ? displayChar : residue);
926 text.append(" (").append(Integer.toString(pos)).append(")");
928 ap.alignFrame.statusBar.setText(text.toString());
934 * Set the status bar message to highlight the first matched position in
939 private void setStatusMessage(SearchResultsI results)
941 AlignmentI al = this.av.getAlignment();
942 int sequenceIndex = al.findIndex(results);
943 if (sequenceIndex == -1)
947 SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
948 for (SearchResultMatchI m : results.getResults())
950 SequenceI seq = m.getSequence();
951 if (seq.getDatasetSequence() != null)
953 seq = seq.getDatasetSequence();
959 * Convert position in sequence (base 1) to sequence character array
962 int start = m.getStart() - m.getSequence().getStart();
963 setStatusMessage(seq, start, sequenceIndex);
973 public void mouseDragged(MouseEvent evt)
975 if (mouseWheelPressed)
977 boolean inSplitFrame = ap.av.getCodingComplement() != null;
978 boolean copyChanges = inSplitFrame && av.isProteinFontAsCdna();
980 int oldWidth = av.getCharWidth();
982 // Which is bigger, left-right or up-down?
983 if (Math.abs(evt.getY() - lastMousePress.getY()) > Math.abs(evt
984 .getX() - lastMousePress.getX()))
987 * on drag up or down, decrement or increment font size
989 int fontSize = av.font.getSize();
990 boolean fontChanged = false;
992 if (evt.getY() < lastMousePress.getY())
997 else if (evt.getY() > lastMousePress.getY())
1010 Font newFont = new Font(av.font.getName(), av.font.getStyle(),
1012 av.setFont(newFont, true);
1013 av.setCharWidth(oldWidth);
1017 ap.av.getCodingComplement().setFont(newFont, true);
1018 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1019 .getSplitViewContainer();
1020 splitFrame.adjustLayout();
1021 splitFrame.repaint();
1028 * on drag left or right, decrement or increment character width
1031 if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
1033 newWidth = av.getCharWidth() - 1;
1034 av.setCharWidth(newWidth);
1036 else if (evt.getX() > lastMousePress.getX())
1038 newWidth = av.getCharWidth() + 1;
1039 av.setCharWidth(newWidth);
1043 ap.paintAlignment(false);
1047 * need to ensure newWidth is set on cdna, regardless of which
1048 * panel the mouse drag happened in; protein will compute its
1049 * character width as 1:1 or 3:1
1051 av.getCodingComplement().setCharWidth(newWidth);
1052 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1053 .getSplitViewContainer();
1054 splitFrame.adjustLayout();
1055 splitFrame.repaint();
1060 FontMetrics fm = getFontMetrics(av.getFont());
1061 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1063 lastMousePress = evt.getPoint();
1070 doMouseDraggedDefineMode(evt);
1074 int res = findColumn(evt);
1081 if ((lastres == -1) || (lastres == res))
1086 if ((res < av.getAlignment().getWidth()) && (res < lastres))
1088 // dragLeft, delete gap
1089 editSequence(false, false, res);
1093 editSequence(true, false, res);
1096 mouseDragging = true;
1097 if (scrollThread != null)
1099 scrollThread.setEvent(evt);
1103 // TODO: Make it more clever than many booleans
1104 synchronized void editSequence(boolean insertGap, boolean editSeq,
1108 int fixedRight = -1;
1109 boolean fixedColumns = false;
1110 SequenceGroup sg = av.getSelectionGroup();
1112 SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1114 // No group, but the sequence may represent a group
1115 if (!groupEditing && av.hasHiddenRows())
1117 if (av.isHiddenRepSequence(seq))
1119 sg = av.getRepresentedSequences(seq);
1120 groupEditing = true;
1124 StringBuilder message = new StringBuilder(64);
1127 message.append("Edit group:");
1128 if (editCommand == null)
1130 editCommand = new EditCommand(
1131 MessageManager.getString("action.edit_group"));
1136 message.append("Edit sequence: " + seq.getName());
1137 String label = seq.getName();
1138 if (label.length() > 10)
1140 label = label.substring(0, 10);
1142 if (editCommand == null)
1144 editCommand = new EditCommand(MessageManager.formatMessage(
1145 "label.edit_params", new String[] { label }));
1151 message.append(" insert ");
1155 message.append(" delete ");
1158 message.append(Math.abs(startres - lastres) + " gaps.");
1159 ap.alignFrame.statusBar.setText(message.toString());
1161 // Are we editing within a selection group?
1163 || (sg != null && sg.getSequences(av.getHiddenRepSequences())
1166 fixedColumns = true;
1168 // sg might be null as the user may only see 1 sequence,
1169 // but the sequence represents a group
1172 if (!av.isHiddenRepSequence(seq))
1177 sg = av.getRepresentedSequences(seq);
1180 fixedLeft = sg.getStartRes();
1181 fixedRight = sg.getEndRes();
1183 if ((startres < fixedLeft && lastres >= fixedLeft)
1184 || (startres >= fixedLeft && lastres < fixedLeft)
1185 || (startres > fixedRight && lastres <= fixedRight)
1186 || (startres <= fixedRight && lastres > fixedRight))
1192 if (fixedLeft > startres)
1194 fixedRight = fixedLeft - 1;
1197 else if (fixedRight < startres)
1199 fixedLeft = fixedRight;
1204 if (av.hasHiddenColumns())
1206 fixedColumns = true;
1207 int y1 = av.getAlignment().getHiddenColumns()
1208 .getHiddenBoundaryLeft(startres);
1209 int y2 = av.getAlignment().getHiddenColumns()
1210 .getHiddenBoundaryRight(startres);
1212 if ((insertGap && startres > y1 && lastres < y1)
1213 || (!insertGap && startres < y2 && lastres > y2))
1219 // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1220 // Selection spans a hidden region
1221 if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1229 fixedRight = y2 - 1;
1236 List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1237 int g, groupSize = vseqs.size();
1238 SequenceI[] groupSeqs = new SequenceI[groupSize];
1239 for (g = 0; g < groupSeqs.length; g++)
1241 groupSeqs[g] = vseqs.get(g);
1247 // If the user has selected the whole sequence, and is dragging to
1248 // the right, we can still extend the alignment and selectionGroup
1249 if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1250 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1252 sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1253 fixedRight = sg.getEndRes();
1256 // Is it valid with fixed columns??
1257 // Find the next gap before the end
1258 // of the visible region boundary
1259 boolean blank = false;
1260 for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1264 for (g = 0; g < groupSize; g++)
1266 for (int j = 0; j < startres - lastres; j++)
1268 if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1283 if (sg.getSize() == av.getAlignment().getHeight())
1285 if ((av.hasHiddenColumns() && startres < av.getAlignment()
1286 .getHiddenColumns().getHiddenBoundaryRight(startres)))
1292 int alWidth = av.getAlignment().getWidth();
1293 if (av.hasHiddenRows())
1295 int hwidth = av.getAlignment().getHiddenSequences()
1297 if (hwidth > alWidth)
1302 // We can still insert gaps if the selectionGroup
1303 // contains all the sequences
1304 sg.setEndRes(sg.getEndRes() + startres - lastres);
1305 fixedRight = alWidth + startres - lastres;
1316 else if (!insertGap)
1318 // / Are we able to delete?
1319 // ie are all columns blank?
1321 for (g = 0; g < groupSize; g++)
1323 for (int j = startres; j < lastres; j++)
1325 if (groupSeqs[g].getLength() <= j)
1330 if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1332 // Not a gap, block edit not valid
1342 // dragging to the right
1343 if (fixedColumns && fixedRight != -1)
1345 for (int j = lastres; j < startres; j++)
1347 insertChar(j, groupSeqs, fixedRight);
1352 appendEdit(Action.INSERT_GAP, groupSeqs, startres, startres
1358 // dragging to the left
1359 if (fixedColumns && fixedRight != -1)
1361 for (int j = lastres; j > startres; j--)
1363 deleteChar(startres, groupSeqs, fixedRight);
1368 appendEdit(Action.DELETE_GAP, groupSeqs, startres, lastres
1375 // ///Editing a single sequence///////////
1379 // dragging to the right
1380 if (fixedColumns && fixedRight != -1)
1382 for (int j = lastres; j < startres; j++)
1384 insertChar(j, new SequenceI[] { seq }, fixedRight);
1389 appendEdit(Action.INSERT_GAP, new SequenceI[] { seq }, lastres,
1390 startres - lastres);
1397 // dragging to the left
1398 if (fixedColumns && fixedRight != -1)
1400 for (int j = lastres; j > startres; j--)
1402 if (!Comparison.isGap(seq.getCharAt(startres)))
1407 deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1412 // could be a keyboard edit trying to delete none gaps
1414 for (int m = startres; m < lastres; m++)
1416 if (!Comparison.isGap(seq.getCharAt(m)))
1425 appendEdit(Action.DELETE_GAP, new SequenceI[] { seq },
1431 {// insertGap==false AND editSeq==TRUE;
1432 if (fixedColumns && fixedRight != -1)
1434 for (int j = lastres; j < startres; j++)
1436 insertChar(j, new SequenceI[] { seq }, fixedRight);
1441 appendEdit(Action.INSERT_NUC, new SequenceI[] { seq }, lastres,
1442 startres - lastres);
1449 seqCanvas.repaint();
1452 void insertChar(int j, SequenceI[] seq, int fixedColumn)
1454 int blankColumn = fixedColumn;
1455 for (int s = 0; s < seq.length; s++)
1457 // Find the next gap before the end of the visible region boundary
1458 // If lastCol > j, theres a boundary after the gap insertion
1460 for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1462 if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1464 // Theres a space, so break and insert the gap
1469 if (blankColumn <= j)
1471 blankColumn = fixedColumn;
1477 appendEdit(Action.DELETE_GAP, seq, blankColumn, 1);
1479 appendEdit(Action.INSERT_GAP, seq, j, 1);
1484 * Helper method to add and perform one edit action.
1491 protected void appendEdit(Action action, SequenceI[] seq, int pos,
1495 final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1496 av.getAlignment().getGapCharacter());
1498 editCommand.appendEdit(edit, av.getAlignment(), true, null);
1501 void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1504 appendEdit(Action.DELETE_GAP, seq, j, 1);
1506 appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1);
1516 public void mouseEntered(MouseEvent e)
1523 if (scrollThread != null)
1525 scrollThread.running = false;
1526 scrollThread = null;
1537 public void mouseExited(MouseEvent e)
1539 if (av.getWrapAlignment())
1546 scrollThread = new ScrollThread();
1551 * Handler for double-click on a position with one or more sequence features.
1552 * Opens the Amend Features dialog to allow feature details to be amended, or
1553 * the feature deleted.
1556 public void mouseClicked(MouseEvent evt)
1558 SequenceGroup sg = null;
1559 SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
1560 if (evt.getClickCount() > 1)
1562 sg = av.getSelectionGroup();
1563 if (sg != null && sg.getSize() == 1
1564 && sg.getEndRes() - sg.getStartRes() < 2)
1566 av.setSelectionGroup(null);
1569 int column = findColumn(evt);
1570 boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
1573 * find features at the position (if not gapped), or straddling
1574 * the position (if at a gap)
1576 List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1577 .findFeaturesAtRes(sequence.getDatasetSequence(),
1578 sequence.findPosition(column));
1581 removeAdjacentFeatures(features, column, sequence);
1584 if (!features.isEmpty())
1587 * highlight the first feature at the position on the alignment
1589 SearchResultsI highlight = new SearchResults();
1590 highlight.addResult(sequence, features.get(0).getBegin(), features
1592 seqCanvas.highlightSearchResults(highlight);
1595 * open the Amend Features dialog; clear highlighting afterwards,
1596 * whether changes were made or not
1598 List<SequenceI> seqs = Collections.singletonList(sequence);
1599 seqCanvas.getFeatureRenderer().amendFeatures(seqs, features, false,
1601 seqCanvas.highlightSearchResults(null);
1607 public void mouseWheelMoved(MouseWheelEvent e)
1610 if (e.getWheelRotation() > 0)
1612 if (e.isShiftDown())
1614 av.getRanges().scrollRight(true);
1619 av.getRanges().scrollUp(false);
1624 if (e.isShiftDown())
1626 av.getRanges().scrollRight(false);
1630 av.getRanges().scrollUp(true);
1633 // TODO Update tooltip for new position.
1642 public void doMousePressedDefineMode(MouseEvent evt)
1644 final int res = findColumn(evt);
1645 final int seq = findSeq(evt);
1647 needOverviewUpdate = false;
1649 startWrapBlock = wrappedBlock;
1651 if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1653 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
1654 .getString("label.cannot_edit_annotations_in_wrapped_view"),
1655 MessageManager.getString("label.wrapped_view_no_edit"),
1656 JvOptionPane.WARNING_MESSAGE);
1660 if (seq < 0 || res < 0)
1665 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1667 if ((sequence == null) || (res > sequence.getLength()))
1672 stretchGroup = av.getSelectionGroup();
1674 if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1676 stretchGroup = av.getAlignment().findGroup(sequence, res);
1677 if (stretchGroup != null)
1679 // only update the current selection if the popup menu has a group to
1681 av.setSelectionGroup(stretchGroup);
1685 if (evt.isPopupTrigger()) // Mac: mousePressed
1692 * defer right-mouse click handling to mouseReleased on Windows
1693 * (where isPopupTrigger() will answer true)
1694 * NB isRightMouseButton is also true for Cmd-click on Mac
1696 if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1703 seqCanvas.cursorX = findColumn(evt);
1704 seqCanvas.cursorY = findSeq(evt);
1705 seqCanvas.repaint();
1709 if (stretchGroup == null)
1711 // Only if left mouse button do we want to change group sizes
1713 // define a new group here
1714 SequenceGroup sg = new SequenceGroup();
1715 sg.setStartRes(res);
1717 sg.addSequence(sequence, false);
1718 av.setSelectionGroup(sg);
1721 if (av.getConservationSelected())
1723 SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1727 if (av.getAbovePIDThreshold())
1729 SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1732 // TODO: stretchGroup will always be not null. Is this a merge error ?
1733 if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1735 // Edit end res position of selected group
1736 changeEndRes = true;
1738 else if ((stretchGroup != null)
1739 && (stretchGroup.getStartRes() == res))
1741 // Edit end res position of selected group
1742 changeStartRes = true;
1744 stretchGroup.getWidth();
1747 seqCanvas.repaint();
1751 * Build and show a pop-up menu at the right-click mouse position
1757 void showPopupMenu(MouseEvent evt)
1759 final int res = findColumn(evt);
1760 final int seq = findSeq(evt);
1761 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1762 List<SequenceFeature> allFeatures = ap.getFeatureRenderer()
1763 .findFeaturesAtRes(sequence.getDatasetSequence(),
1764 sequence.findPosition(res));
1765 List<String> links = new ArrayList<>();
1766 for (SequenceFeature sf : allFeatures)
1768 if (sf.links != null)
1770 for (String link : sf.links)
1777 PopupMenu pop = new PopupMenu(ap, null, links);
1778 pop.show(this, evt.getX(), evt.getY());
1782 * Update the display after mouse up on a selection or group
1785 * mouse released event details
1787 * true if this event is happening after a mouse drag (rather than a
1790 public void doMouseReleasedDefineMode(MouseEvent evt, boolean afterDrag)
1792 if (stretchGroup == null)
1796 // always do this - annotation has own state
1797 // but defer colourscheme update until hidden sequences are passed in
1798 boolean vischange = stretchGroup.recalcConservation(true);
1799 needOverviewUpdate |= vischange && av.isSelectionDefinedGroup()
1801 if (stretchGroup.cs != null)
1803 stretchGroup.cs.alignmentChanged(stretchGroup,
1804 av.getHiddenRepSequences());
1806 ResidueShaderI groupColourScheme = stretchGroup.getGroupColourScheme();
1807 String name = stretchGroup.getName();
1808 if (stretchGroup.cs.conservationApplied())
1810 SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1812 if (stretchGroup.cs.getThreshold() > 0)
1814 SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1817 PaintRefresher.Refresh(this, av.getSequenceSetId());
1818 ap.paintAlignment(needOverviewUpdate);
1819 needOverviewUpdate = false;
1820 changeEndRes = false;
1821 changeStartRes = false;
1822 stretchGroup = null;
1832 public void doMouseDraggedDefineMode(MouseEvent evt)
1834 int res = findColumn(evt);
1835 int y = findSeq(evt);
1837 if (wrappedBlock != startWrapBlock)
1842 if (stretchGroup == null)
1847 if (res >= av.getAlignment().getWidth())
1849 res = av.getAlignment().getWidth() - 1;
1852 if (stretchGroup.getEndRes() == res)
1854 // Edit end res position of selected group
1855 changeEndRes = true;
1857 else if (stretchGroup.getStartRes() == res)
1859 // Edit start res position of selected group
1860 changeStartRes = true;
1863 if (res < av.getRanges().getStartRes())
1865 res = av.getRanges().getStartRes();
1870 if (res > (stretchGroup.getStartRes() - 1))
1872 stretchGroup.setEndRes(res);
1873 needOverviewUpdate |= av.isSelectionDefinedGroup();
1876 else if (changeStartRes)
1878 if (res < (stretchGroup.getEndRes() + 1))
1880 stretchGroup.setStartRes(res);
1881 needOverviewUpdate |= av.isSelectionDefinedGroup();
1885 int dragDirection = 0;
1891 else if (y < oldSeq)
1896 while ((y != oldSeq) && (oldSeq > -1)
1897 && (y < av.getAlignment().getHeight()))
1899 // This routine ensures we don't skip any sequences, as the
1900 // selection is quite slow.
1901 Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1903 oldSeq += dragDirection;
1910 Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1912 if (stretchGroup.getSequences(null).contains(nextSeq))
1914 stretchGroup.deleteSequence(seq, false);
1915 needOverviewUpdate |= av.isSelectionDefinedGroup();
1921 stretchGroup.addSequence(seq, false);
1924 stretchGroup.addSequence(nextSeq, false);
1925 needOverviewUpdate |= av.isSelectionDefinedGroup();
1934 mouseDragging = true;
1936 if (scrollThread != null)
1938 scrollThread.setEvent(evt);
1941 seqCanvas.repaint();
1944 void scrollCanvas(MouseEvent evt)
1948 if (scrollThread != null)
1950 scrollThread.running = false;
1951 scrollThread = null;
1953 mouseDragging = false;
1957 if (scrollThread == null)
1959 scrollThread = new ScrollThread();
1962 mouseDragging = true;
1963 scrollThread.setEvent(evt);
1968 // this class allows scrolling off the bottom of the visible alignment
1969 class ScrollThread extends Thread
1973 boolean running = false;
1975 public ScrollThread()
1980 public void setEvent(MouseEvent e)
1985 public void stopScrolling()
1999 if (mouseDragging && (evt.getY() < 0)
2000 && (av.getRanges().getStartSeq() > 0))
2002 running = av.getRanges().scrollUp(true);
2005 if (mouseDragging && (evt.getY() >= getHeight())
2006 && (av.getAlignment().getHeight() > av.getRanges()
2009 running = av.getRanges().scrollUp(false);
2012 if (mouseDragging && (evt.getX() < 0))
2014 running = av.getRanges().scrollRight(false);
2016 else if (mouseDragging && (evt.getX() >= getWidth()))
2018 running = av.getRanges().scrollRight(true);
2025 } catch (Exception ex)
2033 * modify current selection according to a received message.
2036 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
2037 HiddenColumns hidden, SelectionSource source)
2039 // TODO: fix this hack - source of messages is align viewport, but SeqPanel
2040 // handles selection messages...
2041 // TODO: extend config options to allow user to control if selections may be
2042 // shared between viewports.
2043 boolean iSentTheSelection = (av == source || (source instanceof AlignViewport && ((AlignmentViewport) source)
2044 .getSequenceSetId().equals(av.getSequenceSetId())));
2046 if (iSentTheSelection)
2048 // respond to our own event by updating dependent dialogs
2049 if (ap.getCalculationDialog() != null)
2051 ap.getCalculationDialog().validateCalcTypes();
2057 // process further ?
2058 if (!av.followSelection)
2064 * Ignore the selection if there is one of our own pending.
2066 if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
2072 * Check for selection in a view of which this one is a dna/protein
2075 if (selectionFromTranslation(seqsel, colsel, hidden, source))
2080 // do we want to thread this ? (contention with seqsel and colsel locks, I
2083 * only copy colsel if there is a real intersection between
2084 * sequence selection and this panel's alignment
2086 boolean repaint = false;
2087 boolean copycolsel = false;
2089 SequenceGroup sgroup = null;
2090 if (seqsel != null && seqsel.getSize() > 0)
2092 if (av.getAlignment() == null)
2094 Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2095 + " ViewId=" + av.getViewId()
2096 + " 's alignment is NULL! returning immediately.");
2099 sgroup = seqsel.intersect(av.getAlignment(),
2100 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2101 if ((sgroup != null && sgroup.getSize() > 0))
2106 if (sgroup != null && sgroup.getSize() > 0)
2108 av.setSelectionGroup(sgroup);
2112 av.setSelectionGroup(null);
2114 av.isSelectionGroupChanged(true);
2119 // the current selection is unset or from a previous message
2120 // so import the new colsel.
2121 if (colsel == null || colsel.isEmpty())
2123 if (av.getColumnSelection() != null)
2125 av.getColumnSelection().clear();
2131 // TODO: shift colSel according to the intersecting sequences
2132 if (av.getColumnSelection() == null)
2134 av.setColumnSelection(new ColumnSelection(colsel));
2138 av.getColumnSelection().setElementsFrom(colsel,
2139 av.getAlignment().getHiddenColumns());
2142 av.isColSelChanged(true);
2147 && av.hasHiddenColumns()
2148 && (av.getAlignment().getHiddenColumns() == null))
2150 System.err.println("Bad things");
2152 if (repaint) // always true!
2154 // probably finessing with multiple redraws here
2155 PaintRefresher.Refresh(this, av.getSequenceSetId());
2156 // ap.paintAlignment(false);
2159 // lastly, update dependent dialogs
2160 if (ap.getCalculationDialog() != null)
2162 ap.getCalculationDialog().validateCalcTypes();
2168 * If this panel is a cdna/protein translation view of the selection source,
2169 * tries to map the source selection to a local one, and returns true. Else
2176 protected boolean selectionFromTranslation(SequenceGroup seqsel,
2177 ColumnSelection colsel, HiddenColumns hidden,
2178 SelectionSource source)
2180 if (!(source instanceof AlignViewportI))
2184 final AlignViewportI sourceAv = (AlignViewportI) source;
2185 if (sourceAv.getCodingComplement() != av
2186 && av.getCodingComplement() != sourceAv)
2192 * Map sequence selection
2194 SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2195 av.setSelectionGroup(sg);
2196 av.isSelectionGroupChanged(true);
2199 * Map column selection
2201 // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2203 ColumnSelection cs = new ColumnSelection();
2204 HiddenColumns hs = new HiddenColumns();
2205 MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2206 av.setColumnSelection(cs);
2207 av.getAlignment().setHiddenColumns(hs);
2209 // lastly, update any dependent dialogs
2210 if (ap.getCalculationDialog() != null)
2212 ap.getCalculationDialog().validateCalcTypes();
2215 PaintRefresher.Refresh(this, av.getSequenceSetId());