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 int startRes = av.getRanges().getStartRes();
193 if (av.getWrapAlignment())
196 int hgap = av.getCharHeight();
197 if (av.getScaleAboveWrapped())
199 hgap += av.getCharHeight();
202 int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
203 + hgap + seqCanvas.getAnnotationHeight();
207 x = Math.max(0, x - seqCanvas.LABEL_WEST);
209 int cwidth = seqCanvas.getWrappedCanvasWidth(this.getWidth());
215 wrappedBlock = y / cHeight;
216 wrappedBlock += startRes / cwidth;
217 // allow for wrapped view scrolled right (possible from Overview)
218 int startOffset = startRes % cwidth;
219 res = wrappedBlock * cwidth
220 + Math.min(cwidth - 1, startOffset + x / av.getCharWidth());
224 if (x > seqCanvas.getX() + seqCanvas.getWidth())
226 // make sure we calculate relative to visible alignment, rather than
228 x = seqCanvas.getX() + seqCanvas.getWidth();
230 res = (x / av.getCharWidth()) + startRes;
231 if (res > av.getRanges().getEndRes())
234 res = av.getRanges().getEndRes();
238 if (av.hasHiddenColumns())
240 res = av.getAlignment().getHiddenColumns()
241 .adjustForHiddenColumns(res);
248 int findSeq(MouseEvent evt)
253 if (av.getWrapAlignment())
255 int hgap = av.getCharHeight();
256 if (av.getScaleAboveWrapped())
258 hgap += av.getCharHeight();
261 int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
262 + hgap + seqCanvas.getAnnotationHeight();
266 seq = Math.min((y % cHeight) / av.getCharHeight(), av.getAlignment()
271 seq = Math.min((y / av.getCharHeight())
272 + av.getRanges().getStartSeq(),
274 .getAlignment().getHeight() - 1);
281 * When all of a sequence of edits are complete, put the resulting edit list
282 * on the history stack (undo list), and reset flags for editing in progress.
288 if (editCommand != null && editCommand.getSize() > 0)
290 ap.alignFrame.addHistoryItem(editCommand);
291 av.firePropertyChange("alignment", null, av.getAlignment()
297 * Tidy up come what may...
302 groupEditing = false;
311 seqCanvas.cursorY = getKeyboardNo1() - 1;
315 void setCursorColumn()
317 seqCanvas.cursorX = getKeyboardNo1() - 1;
321 void setCursorRowAndColumn()
323 if (keyboardNo2 == null)
325 keyboardNo2 = new StringBuffer();
329 seqCanvas.cursorX = getKeyboardNo1() - 1;
330 seqCanvas.cursorY = getKeyboardNo2() - 1;
335 void setCursorPosition()
337 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
339 seqCanvas.cursorX = sequence.findIndex(getKeyboardNo1()) - 1;
343 void moveCursor(int dx, int dy)
345 seqCanvas.cursorX += dx;
346 seqCanvas.cursorY += dy;
348 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
350 if (av.hasHiddenColumns()
351 && !hidden.isVisible(seqCanvas.cursorX))
353 int original = seqCanvas.cursorX - dx;
354 int maxWidth = av.getAlignment().getWidth();
356 while (!hidden.isVisible(seqCanvas.cursorX)
357 && seqCanvas.cursorX < maxWidth && seqCanvas.cursorX > 0)
359 seqCanvas.cursorX += dx;
362 if (seqCanvas.cursorX >= maxWidth
363 || !hidden.isVisible(seqCanvas.cursorX))
365 seqCanvas.cursorX = original;
372 void scrollToVisible()
374 if (seqCanvas.cursorX < 0)
376 seqCanvas.cursorX = 0;
378 else if (seqCanvas.cursorX > av.getAlignment().getWidth() - 1)
380 seqCanvas.cursorX = av.getAlignment().getWidth() - 1;
383 if (seqCanvas.cursorY < 0)
385 seqCanvas.cursorY = 0;
387 else if (seqCanvas.cursorY > av.getAlignment().getHeight() - 1)
389 seqCanvas.cursorY = av.getAlignment().getHeight() - 1;
393 if (av.getWrapAlignment())
395 av.getRanges().scrollToWrappedVisible(seqCanvas.cursorX);
399 av.getRanges().scrollToVisible(seqCanvas.cursorX, seqCanvas.cursorY);
401 setStatusMessage(av.getAlignment().getSequenceAt(seqCanvas.cursorY),
402 seqCanvas.cursorX, seqCanvas.cursorY);
407 void setSelectionAreaAtCursor(boolean topLeft)
409 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
411 if (av.getSelectionGroup() != null)
413 SequenceGroup sg = av.getSelectionGroup();
414 // Find the top and bottom of this group
415 int min = av.getAlignment().getHeight(), max = 0;
416 for (int i = 0; i < sg.getSize(); i++)
418 int index = av.getAlignment().findIndex(sg.getSequenceAt(i));
433 sg.setStartRes(seqCanvas.cursorX);
434 if (sg.getEndRes() < seqCanvas.cursorX)
436 sg.setEndRes(seqCanvas.cursorX);
439 min = seqCanvas.cursorY;
443 sg.setEndRes(seqCanvas.cursorX);
444 if (sg.getStartRes() > seqCanvas.cursorX)
446 sg.setStartRes(seqCanvas.cursorX);
449 max = seqCanvas.cursorY + 1;
454 // Only the user can do this
455 av.setSelectionGroup(null);
459 // Now add any sequences between min and max
460 sg.getSequences(null).clear();
461 for (int i = min; i < max; i++)
463 sg.addSequence(av.getAlignment().getSequenceAt(i), false);
468 if (av.getSelectionGroup() == null)
470 SequenceGroup sg = new SequenceGroup();
471 sg.setStartRes(seqCanvas.cursorX);
472 sg.setEndRes(seqCanvas.cursorX);
473 sg.addSequence(sequence, false);
474 av.setSelectionGroup(sg);
477 ap.paintAlignment(false);
481 void insertGapAtCursor(boolean group)
483 groupEditing = group;
484 startseq = seqCanvas.cursorY;
485 lastres = seqCanvas.cursorX;
486 editSequence(true, false, seqCanvas.cursorX + getKeyboardNo1());
490 void deleteGapAtCursor(boolean group)
492 groupEditing = group;
493 startseq = seqCanvas.cursorY;
494 lastres = seqCanvas.cursorX + getKeyboardNo1();
495 editSequence(false, false, seqCanvas.cursorX);
499 void insertNucAtCursor(boolean group, String nuc)
501 // TODO not called - delete?
502 groupEditing = group;
503 startseq = seqCanvas.cursorY;
504 lastres = seqCanvas.cursorX;
505 editSequence(false, true, seqCanvas.cursorX + getKeyboardNo1());
509 void numberPressed(char value)
511 if (keyboardNo1 == null)
513 keyboardNo1 = new StringBuffer();
516 if (keyboardNo2 != null)
518 keyboardNo2.append(value);
522 keyboardNo1.append(value);
530 if (keyboardNo1 != null)
532 int value = Integer.parseInt(keyboardNo1.toString());
536 } catch (Exception x)
547 if (keyboardNo2 != null)
549 int value = Integer.parseInt(keyboardNo2.toString());
553 } catch (Exception x)
567 public void mouseReleased(MouseEvent evt)
569 boolean didDrag = mouseDragging; // did we come here after a drag
570 mouseDragging = false;
571 mouseWheelPressed = false;
573 if (evt.isPopupTrigger()) // Windows: mouseReleased
582 doMouseReleasedDefineMode(evt, didDrag);
596 public void mousePressed(MouseEvent evt)
598 lastMousePress = evt.getPoint();
600 if (SwingUtilities.isMiddleMouseButton(evt))
602 mouseWheelPressed = true;
606 boolean isControlDown = Platform.isControlDown(evt);
607 if (evt.isShiftDown() || isControlDown)
617 doMousePressedDefineMode(evt);
621 int seq = findSeq(evt);
622 int res = findColumn(evt);
624 if (seq < 0 || res < 0)
629 if ((seq < av.getAlignment().getHeight())
630 && (res < av.getAlignment().getSequenceAt(seq).getLength()))
647 public void mouseOverSequence(SequenceI sequence, int index, int pos)
649 String tmp = sequence.hashCode() + " " + index + " " + pos;
651 if (lastMessage == null || !lastMessage.equals(tmp))
653 // System.err.println("mouseOver Sequence: "+tmp);
654 ssm.mouseOverSequence(sequence, index, pos, av);
660 * Highlight the mapped region described by the search results object (unless
661 * unchanged). This supports highlight of protein while mousing over linked
662 * cDNA and vice versa. The status bar is also updated to show the location of
663 * the start of the highlighted region.
666 public void highlightSequence(SearchResultsI results)
668 if (results == null || results.equals(lastSearchResults))
672 lastSearchResults = results;
674 if (av.isFollowHighlight())
676 // don't allow highlight of protein/cDNA to also scroll a complementary
677 // panel,as this sets up a feedback loop (scrolling panel 1 causes moused
678 // over residue to change abruptly, causing highlighted residue in panel 2
679 // to change, causing a scroll in panel 1 etc)
680 ap.setToScrollComplementPanel(false);
681 if (ap.scrollToPosition(results, false))
683 seqCanvas.revalidate();
685 ap.setToScrollComplementPanel(true);
687 setStatusMessage(results);
688 seqCanvas.highlightSearchResults(results);
692 public VamsasSource getVamsasSource()
694 return this.ap == null ? null : this.ap.av;
698 public void updateColours(SequenceI seq, int index)
700 System.out.println("update the seqPanel colours");
711 public void mouseMoved(MouseEvent evt)
715 // This is because MacOSX creates a mouseMoved
716 // If control is down, other platforms will not.
720 final int column = findColumn(evt);
721 int seq = findSeq(evt);
722 if (column < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
727 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
729 if (column >= sequence.getLength())
735 * set status bar message, returning residue position in sequence
737 boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
738 final int pos = setStatusMessage(sequence, column, seq);
739 if (ssm != null && !isGapped)
741 mouseOverSequence(sequence, column, pos);
744 tooltipText.setLength(6); // Cuts the buffer back to <html>
746 SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
749 for (int g = 0; g < groups.length; g++)
751 if (groups[g].getStartRes() <= column
752 && groups[g].getEndRes() >= column)
754 if (!groups[g].getName().startsWith("JTreeGroup")
755 && !groups[g].getName().startsWith("JGroup"))
757 tooltipText.append(groups[g].getName());
760 if (groups[g].getDescription() != null)
762 tooltipText.append(": " + groups[g].getDescription());
769 * add any features at the position to the tooltip; if over a gap, only
770 * add features that straddle the gap (pos may be the residue before or
773 if (av.isShowSequenceFeatures())
775 List<SequenceFeature> features = ap.getFeatureRenderer()
776 .findFeaturesAtRes(sequence.getDatasetSequence(), pos);
779 removeAdjacentFeatures(features, column + 1, sequence);
781 seqARep.appendFeatures(tooltipText, pos, features,
782 this.ap.getSeqPanel().seqCanvas.fr.getMinMax());
784 if (tooltipText.length() == 6) // <html>
786 setToolTipText(null);
791 if (lastTooltip == null
792 || !lastTooltip.equals(tooltipText.toString()))
794 String formatedTooltipText = JvSwingUtils.wrapTooltip(true,
795 tooltipText.toString());
796 // String formatedTooltipText = tooltipText.toString();
797 setToolTipText(formatedTooltipText);
798 lastTooltip = tooltipText.toString();
806 * Removes from the list of features any that start after, or end before, the
807 * given column position. This allows us to retain only those features
808 * adjacent to a gapped position that straddle the position. Contact features
809 * that 'straddle' the position are also removed, since they are not 'at' the
814 * alignment column (1..)
817 protected void removeAdjacentFeatures(List<SequenceFeature> features,
818 final int column, SequenceI sequence)
820 // TODO should this be an AlignViewController method (and reused by applet)?
821 ListIterator<SequenceFeature> it = features.listIterator();
824 SequenceFeature sf = it.next();
825 if (sf.isContactFeature()
826 || sequence.findIndex(sf.getBegin()) > column
827 || sequence.findIndex(sf.getEnd()) < column)
834 private Point lastp = null;
839 * @see javax.swing.JComponent#getToolTipLocation(java.awt.event.MouseEvent)
842 public Point getToolTipLocation(MouseEvent event)
844 int x = event.getX(), w = getWidth();
845 int wdth = (w - x < 200) ? -(w / 2) : 5; // switch sides when tooltip is too
848 if (!event.isShiftDown() || p == null)
850 p = (tooltipText != null && tooltipText.length() > 6) ? new Point(
851 event.getX() + wdth, event.getY() - 20) : null;
854 * TODO: try to modify position region is not obcured by tooltip
862 * set when the current UI interaction has resulted in a change that requires
863 * overview shading to be recalculated. this could be changed to something
864 * more expressive that indicates what actually has changed, so selective
865 * redraws can be applied
867 private boolean needOverviewUpdate = false; // TODO: refactor to avcontroller
870 * set if av.getSelectionGroup() refers to a group that is defined on the
871 * alignment view, rather than a transient selection
873 // private boolean editingDefinedGroup = false; // TODO: refactor to
874 // avcontroller or viewModel
877 * Sets the status message in alignment panel, showing the sequence number
878 * (index) and id, and residue and residue position if not at a gap, for the
879 * given sequence and column position. Returns the residue position returned
880 * by Sequence.findPosition. Note this may be for the nearest adjacent residue
881 * if at a gapped position.
884 * aligned sequence object
888 * index of sequence in alignment
889 * @return sequence position of residue at column, or adjacent residue if at a
892 int setStatusMessage(SequenceI sequence, final int column, int seq)
894 StringBuilder text = new StringBuilder(32);
897 * Sequence number (if known), and sequence name.
899 String seqno = seq == -1 ? "" : " " + (seq + 1);
900 text.append("Sequence").append(seqno).append(" ID: ")
901 .append(sequence.getName());
903 String residue = null;
906 * Try to translate the display character to residue name (null for gap).
908 final String displayChar = String.valueOf(sequence.getCharAt(column));
909 boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
910 int pos = sequence.findPosition(column);
914 boolean nucleotide = av.getAlignment().isNucleotide();
917 residue = ResidueProperties.nucleotideName.get(displayChar);
921 residue = "X".equalsIgnoreCase(displayChar) ? "X" : ("*"
922 .equals(displayChar) ? "STOP"
923 : ResidueProperties.aa2Triplet.get(displayChar));
925 text.append(" ").append(nucleotide ? "Nucleotide" : "Residue")
926 .append(": ").append(residue == null ? displayChar : residue);
928 text.append(" (").append(Integer.toString(pos)).append(")");
930 ap.alignFrame.statusBar.setText(text.toString());
936 * Set the status bar message to highlight the first matched position in
941 private void setStatusMessage(SearchResultsI results)
943 AlignmentI al = this.av.getAlignment();
944 int sequenceIndex = al.findIndex(results);
945 if (sequenceIndex == -1)
949 SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
950 for (SearchResultMatchI m : results.getResults())
952 SequenceI seq = m.getSequence();
953 if (seq.getDatasetSequence() != null)
955 seq = seq.getDatasetSequence();
961 * Convert position in sequence (base 1) to sequence character array
964 int start = m.getStart() - m.getSequence().getStart();
965 setStatusMessage(seq, start, sequenceIndex);
975 public void mouseDragged(MouseEvent evt)
977 if (mouseWheelPressed)
979 boolean inSplitFrame = ap.av.getCodingComplement() != null;
980 boolean copyChanges = inSplitFrame && av.isProteinFontAsCdna();
982 int oldWidth = av.getCharWidth();
984 // Which is bigger, left-right or up-down?
985 if (Math.abs(evt.getY() - lastMousePress.getY()) > Math.abs(evt
986 .getX() - lastMousePress.getX()))
989 * on drag up or down, decrement or increment font size
991 int fontSize = av.font.getSize();
992 boolean fontChanged = false;
994 if (evt.getY() < lastMousePress.getY())
999 else if (evt.getY() > lastMousePress.getY())
1012 Font newFont = new Font(av.font.getName(), av.font.getStyle(),
1014 av.setFont(newFont, true);
1015 av.setCharWidth(oldWidth);
1019 ap.av.getCodingComplement().setFont(newFont, true);
1020 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1021 .getSplitViewContainer();
1022 splitFrame.adjustLayout();
1023 splitFrame.repaint();
1030 * on drag left or right, decrement or increment character width
1033 if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
1035 newWidth = av.getCharWidth() - 1;
1036 av.setCharWidth(newWidth);
1038 else if (evt.getX() > lastMousePress.getX())
1040 newWidth = av.getCharWidth() + 1;
1041 av.setCharWidth(newWidth);
1045 ap.paintAlignment(false);
1049 * need to ensure newWidth is set on cdna, regardless of which
1050 * panel the mouse drag happened in; protein will compute its
1051 * character width as 1:1 or 3:1
1053 av.getCodingComplement().setCharWidth(newWidth);
1054 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1055 .getSplitViewContainer();
1056 splitFrame.adjustLayout();
1057 splitFrame.repaint();
1062 FontMetrics fm = getFontMetrics(av.getFont());
1063 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1065 lastMousePress = evt.getPoint();
1072 doMouseDraggedDefineMode(evt);
1076 int res = findColumn(evt);
1083 if ((lastres == -1) || (lastres == res))
1088 if ((res < av.getAlignment().getWidth()) && (res < lastres))
1090 // dragLeft, delete gap
1091 editSequence(false, false, res);
1095 editSequence(true, false, res);
1098 mouseDragging = true;
1099 if (scrollThread != null)
1101 scrollThread.setEvent(evt);
1105 // TODO: Make it more clever than many booleans
1106 synchronized void editSequence(boolean insertGap, boolean editSeq,
1110 int fixedRight = -1;
1111 boolean fixedColumns = false;
1112 SequenceGroup sg = av.getSelectionGroup();
1114 SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1116 // No group, but the sequence may represent a group
1117 if (!groupEditing && av.hasHiddenRows())
1119 if (av.isHiddenRepSequence(seq))
1121 sg = av.getRepresentedSequences(seq);
1122 groupEditing = true;
1126 StringBuilder message = new StringBuilder(64);
1129 message.append("Edit group:");
1130 if (editCommand == null)
1132 editCommand = new EditCommand(
1133 MessageManager.getString("action.edit_group"));
1138 message.append("Edit sequence: " + seq.getName());
1139 String label = seq.getName();
1140 if (label.length() > 10)
1142 label = label.substring(0, 10);
1144 if (editCommand == null)
1146 editCommand = new EditCommand(MessageManager.formatMessage(
1147 "label.edit_params", new String[] { label }));
1153 message.append(" insert ");
1157 message.append(" delete ");
1160 message.append(Math.abs(startres - lastres) + " gaps.");
1161 ap.alignFrame.statusBar.setText(message.toString());
1163 // Are we editing within a selection group?
1165 || (sg != null && sg.getSequences(av.getHiddenRepSequences())
1168 fixedColumns = true;
1170 // sg might be null as the user may only see 1 sequence,
1171 // but the sequence represents a group
1174 if (!av.isHiddenRepSequence(seq))
1179 sg = av.getRepresentedSequences(seq);
1182 fixedLeft = sg.getStartRes();
1183 fixedRight = sg.getEndRes();
1185 if ((startres < fixedLeft && lastres >= fixedLeft)
1186 || (startres >= fixedLeft && lastres < fixedLeft)
1187 || (startres > fixedRight && lastres <= fixedRight)
1188 || (startres <= fixedRight && lastres > fixedRight))
1194 if (fixedLeft > startres)
1196 fixedRight = fixedLeft - 1;
1199 else if (fixedRight < startres)
1201 fixedLeft = fixedRight;
1206 if (av.hasHiddenColumns())
1208 fixedColumns = true;
1209 int y1 = av.getAlignment().getHiddenColumns()
1210 .getHiddenBoundaryLeft(startres);
1211 int y2 = av.getAlignment().getHiddenColumns()
1212 .getHiddenBoundaryRight(startres);
1214 if ((insertGap && startres > y1 && lastres < y1)
1215 || (!insertGap && startres < y2 && lastres > y2))
1221 // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1222 // Selection spans a hidden region
1223 if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1231 fixedRight = y2 - 1;
1238 List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1239 int g, groupSize = vseqs.size();
1240 SequenceI[] groupSeqs = new SequenceI[groupSize];
1241 for (g = 0; g < groupSeqs.length; g++)
1243 groupSeqs[g] = vseqs.get(g);
1249 // If the user has selected the whole sequence, and is dragging to
1250 // the right, we can still extend the alignment and selectionGroup
1251 if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1252 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1254 sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1255 fixedRight = sg.getEndRes();
1258 // Is it valid with fixed columns??
1259 // Find the next gap before the end
1260 // of the visible region boundary
1261 boolean blank = false;
1262 for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1266 for (g = 0; g < groupSize; g++)
1268 for (int j = 0; j < startres - lastres; j++)
1270 if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1285 if (sg.getSize() == av.getAlignment().getHeight())
1287 if ((av.hasHiddenColumns() && startres < av.getAlignment()
1288 .getHiddenColumns().getHiddenBoundaryRight(startres)))
1294 int alWidth = av.getAlignment().getWidth();
1295 if (av.hasHiddenRows())
1297 int hwidth = av.getAlignment().getHiddenSequences()
1299 if (hwidth > alWidth)
1304 // We can still insert gaps if the selectionGroup
1305 // contains all the sequences
1306 sg.setEndRes(sg.getEndRes() + startres - lastres);
1307 fixedRight = alWidth + startres - lastres;
1318 else if (!insertGap)
1320 // / Are we able to delete?
1321 // ie are all columns blank?
1323 for (g = 0; g < groupSize; g++)
1325 for (int j = startres; j < lastres; j++)
1327 if (groupSeqs[g].getLength() <= j)
1332 if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1334 // Not a gap, block edit not valid
1344 // dragging to the right
1345 if (fixedColumns && fixedRight != -1)
1347 for (int j = lastres; j < startres; j++)
1349 insertChar(j, groupSeqs, fixedRight);
1354 appendEdit(Action.INSERT_GAP, groupSeqs, startres, startres
1360 // dragging to the left
1361 if (fixedColumns && fixedRight != -1)
1363 for (int j = lastres; j > startres; j--)
1365 deleteChar(startres, groupSeqs, fixedRight);
1370 appendEdit(Action.DELETE_GAP, groupSeqs, startres, lastres
1377 // ///Editing a single sequence///////////
1381 // dragging to the right
1382 if (fixedColumns && fixedRight != -1)
1384 for (int j = lastres; j < startres; j++)
1386 insertChar(j, new SequenceI[] { seq }, fixedRight);
1391 appendEdit(Action.INSERT_GAP, new SequenceI[] { seq }, lastres,
1392 startres - lastres);
1399 // dragging to the left
1400 if (fixedColumns && fixedRight != -1)
1402 for (int j = lastres; j > startres; j--)
1404 if (!Comparison.isGap(seq.getCharAt(startres)))
1409 deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1414 // could be a keyboard edit trying to delete none gaps
1416 for (int m = startres; m < lastres; m++)
1418 if (!Comparison.isGap(seq.getCharAt(m)))
1427 appendEdit(Action.DELETE_GAP, new SequenceI[] { seq },
1433 {// insertGap==false AND editSeq==TRUE;
1434 if (fixedColumns && fixedRight != -1)
1436 for (int j = lastres; j < startres; j++)
1438 insertChar(j, new SequenceI[] { seq }, fixedRight);
1443 appendEdit(Action.INSERT_NUC, new SequenceI[] { seq }, lastres,
1444 startres - lastres);
1451 seqCanvas.repaint();
1454 void insertChar(int j, SequenceI[] seq, int fixedColumn)
1456 int blankColumn = fixedColumn;
1457 for (int s = 0; s < seq.length; s++)
1459 // Find the next gap before the end of the visible region boundary
1460 // If lastCol > j, theres a boundary after the gap insertion
1462 for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1464 if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1466 // Theres a space, so break and insert the gap
1471 if (blankColumn <= j)
1473 blankColumn = fixedColumn;
1479 appendEdit(Action.DELETE_GAP, seq, blankColumn, 1);
1481 appendEdit(Action.INSERT_GAP, seq, j, 1);
1486 * Helper method to add and perform one edit action.
1493 protected void appendEdit(Action action, SequenceI[] seq, int pos,
1497 final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1498 av.getAlignment().getGapCharacter());
1500 editCommand.appendEdit(edit, av.getAlignment(), true, null);
1503 void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1506 appendEdit(Action.DELETE_GAP, seq, j, 1);
1508 appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1);
1518 public void mouseEntered(MouseEvent e)
1525 if (scrollThread != null)
1527 scrollThread.running = false;
1528 scrollThread = null;
1539 public void mouseExited(MouseEvent e)
1541 if (av.getWrapAlignment())
1548 scrollThread = new ScrollThread();
1553 * Handler for double-click on a position with one or more sequence features.
1554 * Opens the Amend Features dialog to allow feature details to be amended, or
1555 * the feature deleted.
1558 public void mouseClicked(MouseEvent evt)
1560 SequenceGroup sg = null;
1561 SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
1562 if (evt.getClickCount() > 1)
1564 sg = av.getSelectionGroup();
1565 if (sg != null && sg.getSize() == 1
1566 && sg.getEndRes() - sg.getStartRes() < 2)
1568 av.setSelectionGroup(null);
1571 int column = findColumn(evt);
1572 boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
1575 * find features at the position (if not gapped), or straddling
1576 * the position (if at a gap)
1578 List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1579 .findFeaturesAtRes(sequence.getDatasetSequence(),
1580 sequence.findPosition(column));
1583 removeAdjacentFeatures(features, column, sequence);
1586 if (!features.isEmpty())
1589 * highlight the first feature at the position on the alignment
1591 SearchResultsI highlight = new SearchResults();
1592 highlight.addResult(sequence, features.get(0).getBegin(), features
1594 seqCanvas.highlightSearchResults(highlight);
1597 * open the Amend Features dialog; clear highlighting afterwards,
1598 * whether changes were made or not
1600 List<SequenceI> seqs = Collections.singletonList(sequence);
1601 seqCanvas.getFeatureRenderer().amendFeatures(seqs, features, false,
1603 seqCanvas.highlightSearchResults(null);
1609 public void mouseWheelMoved(MouseWheelEvent e)
1612 if (e.getWheelRotation() > 0)
1614 if (e.isShiftDown())
1616 av.getRanges().scrollRight(true);
1621 av.getRanges().scrollUp(false);
1626 if (e.isShiftDown())
1628 av.getRanges().scrollRight(false);
1632 av.getRanges().scrollUp(true);
1635 // TODO Update tooltip for new position.
1644 public void doMousePressedDefineMode(MouseEvent evt)
1646 final int res = findColumn(evt);
1647 final int seq = findSeq(evt);
1649 needOverviewUpdate = false;
1651 startWrapBlock = wrappedBlock;
1653 if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1655 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
1656 .getString("label.cannot_edit_annotations_in_wrapped_view"),
1657 MessageManager.getString("label.wrapped_view_no_edit"),
1658 JvOptionPane.WARNING_MESSAGE);
1662 if (seq < 0 || res < 0)
1667 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1669 if ((sequence == null) || (res > sequence.getLength()))
1674 stretchGroup = av.getSelectionGroup();
1676 if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1678 stretchGroup = av.getAlignment().findGroup(sequence, res);
1679 if (stretchGroup != null)
1681 // only update the current selection if the popup menu has a group to
1683 av.setSelectionGroup(stretchGroup);
1687 if (evt.isPopupTrigger()) // Mac: mousePressed
1694 * defer right-mouse click handling to mouseReleased on Windows
1695 * (where isPopupTrigger() will answer true)
1696 * NB isRightMouseButton is also true for Cmd-click on Mac
1698 if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1705 seqCanvas.cursorX = findColumn(evt);
1706 seqCanvas.cursorY = findSeq(evt);
1707 seqCanvas.repaint();
1711 if (stretchGroup == null)
1713 // Only if left mouse button do we want to change group sizes
1715 // define a new group here
1716 SequenceGroup sg = new SequenceGroup();
1717 sg.setStartRes(res);
1719 sg.addSequence(sequence, false);
1720 av.setSelectionGroup(sg);
1723 if (av.getConservationSelected())
1725 SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1729 if (av.getAbovePIDThreshold())
1731 SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1734 // TODO: stretchGroup will always be not null. Is this a merge error ?
1735 if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1737 // Edit end res position of selected group
1738 changeEndRes = true;
1740 else if ((stretchGroup != null)
1741 && (stretchGroup.getStartRes() == res))
1743 // Edit end res position of selected group
1744 changeStartRes = true;
1746 stretchGroup.getWidth();
1749 seqCanvas.repaint();
1753 * Build and show a pop-up menu at the right-click mouse position
1759 void showPopupMenu(MouseEvent evt)
1761 final int res = findColumn(evt);
1762 final int seq = findSeq(evt);
1763 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1764 List<SequenceFeature> allFeatures = ap.getFeatureRenderer()
1765 .findFeaturesAtRes(sequence.getDatasetSequence(),
1766 sequence.findPosition(res));
1767 List<String> links = new ArrayList<>();
1768 for (SequenceFeature sf : allFeatures)
1770 if (sf.links != null)
1772 for (String link : sf.links)
1779 PopupMenu pop = new PopupMenu(ap, null, links);
1780 pop.show(this, evt.getX(), evt.getY());
1784 * Update the display after mouse up on a selection or group
1787 * mouse released event details
1789 * true if this event is happening after a mouse drag (rather than a
1792 public void doMouseReleasedDefineMode(MouseEvent evt, boolean afterDrag)
1794 if (stretchGroup == null)
1798 // always do this - annotation has own state
1799 // but defer colourscheme update until hidden sequences are passed in
1800 boolean vischange = stretchGroup.recalcConservation(true);
1801 needOverviewUpdate |= vischange && av.isSelectionDefinedGroup()
1803 if (stretchGroup.cs != null)
1805 stretchGroup.cs.alignmentChanged(stretchGroup,
1806 av.getHiddenRepSequences());
1808 ResidueShaderI groupColourScheme = stretchGroup.getGroupColourScheme();
1809 String name = stretchGroup.getName();
1810 if (stretchGroup.cs.conservationApplied())
1812 SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1814 if (stretchGroup.cs.getThreshold() > 0)
1816 SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1819 PaintRefresher.Refresh(this, av.getSequenceSetId());
1820 ap.paintAlignment(needOverviewUpdate);
1821 needOverviewUpdate = false;
1822 changeEndRes = false;
1823 changeStartRes = false;
1824 stretchGroup = null;
1834 public void doMouseDraggedDefineMode(MouseEvent evt)
1836 int res = findColumn(evt);
1837 int y = findSeq(evt);
1839 if (wrappedBlock != startWrapBlock)
1844 if (stretchGroup == null)
1849 if (res >= av.getAlignment().getWidth())
1851 res = av.getAlignment().getWidth() - 1;
1854 if (stretchGroup.getEndRes() == res)
1856 // Edit end res position of selected group
1857 changeEndRes = true;
1859 else if (stretchGroup.getStartRes() == res)
1861 // Edit start res position of selected group
1862 changeStartRes = true;
1865 if (res < av.getRanges().getStartRes())
1867 res = av.getRanges().getStartRes();
1872 if (res > (stretchGroup.getStartRes() - 1))
1874 stretchGroup.setEndRes(res);
1875 needOverviewUpdate |= av.isSelectionDefinedGroup();
1878 else if (changeStartRes)
1880 if (res < (stretchGroup.getEndRes() + 1))
1882 stretchGroup.setStartRes(res);
1883 needOverviewUpdate |= av.isSelectionDefinedGroup();
1887 int dragDirection = 0;
1893 else if (y < oldSeq)
1898 while ((y != oldSeq) && (oldSeq > -1)
1899 && (y < av.getAlignment().getHeight()))
1901 // This routine ensures we don't skip any sequences, as the
1902 // selection is quite slow.
1903 Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1905 oldSeq += dragDirection;
1912 Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1914 if (stretchGroup.getSequences(null).contains(nextSeq))
1916 stretchGroup.deleteSequence(seq, false);
1917 needOverviewUpdate |= av.isSelectionDefinedGroup();
1923 stretchGroup.addSequence(seq, false);
1926 stretchGroup.addSequence(nextSeq, false);
1927 needOverviewUpdate |= av.isSelectionDefinedGroup();
1936 mouseDragging = true;
1938 if (scrollThread != null)
1940 scrollThread.setEvent(evt);
1943 seqCanvas.repaint();
1946 void scrollCanvas(MouseEvent evt)
1950 if (scrollThread != null)
1952 scrollThread.running = false;
1953 scrollThread = null;
1955 mouseDragging = false;
1959 if (scrollThread == null)
1961 scrollThread = new ScrollThread();
1964 mouseDragging = true;
1965 scrollThread.setEvent(evt);
1970 // this class allows scrolling off the bottom of the visible alignment
1971 class ScrollThread extends Thread
1975 boolean running = false;
1977 public ScrollThread()
1982 public void setEvent(MouseEvent e)
1987 public void stopScrolling()
2001 if (mouseDragging && (evt.getY() < 0)
2002 && (av.getRanges().getStartSeq() > 0))
2004 running = av.getRanges().scrollUp(true);
2007 if (mouseDragging && (evt.getY() >= getHeight())
2008 && (av.getAlignment().getHeight() > av.getRanges()
2011 running = av.getRanges().scrollUp(false);
2014 if (mouseDragging && (evt.getX() < 0))
2016 running = av.getRanges().scrollRight(false);
2018 else if (mouseDragging && (evt.getX() >= getWidth()))
2020 running = av.getRanges().scrollRight(true);
2027 } catch (Exception ex)
2035 * modify current selection according to a received message.
2038 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
2039 HiddenColumns hidden, SelectionSource source)
2041 // TODO: fix this hack - source of messages is align viewport, but SeqPanel
2042 // handles selection messages...
2043 // TODO: extend config options to allow user to control if selections may be
2044 // shared between viewports.
2045 boolean iSentTheSelection = (av == source || (source instanceof AlignViewport && ((AlignmentViewport) source)
2046 .getSequenceSetId().equals(av.getSequenceSetId())));
2048 if (iSentTheSelection)
2050 // respond to our own event by updating dependent dialogs
2051 if (ap.getCalculationDialog() != null)
2053 ap.getCalculationDialog().validateCalcTypes();
2059 // process further ?
2060 if (!av.followSelection)
2066 * Ignore the selection if there is one of our own pending.
2068 if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
2074 * Check for selection in a view of which this one is a dna/protein
2077 if (selectionFromTranslation(seqsel, colsel, hidden, source))
2082 // do we want to thread this ? (contention with seqsel and colsel locks, I
2085 * only copy colsel if there is a real intersection between
2086 * sequence selection and this panel's alignment
2088 boolean repaint = false;
2089 boolean copycolsel = false;
2091 SequenceGroup sgroup = null;
2092 if (seqsel != null && seqsel.getSize() > 0)
2094 if (av.getAlignment() == null)
2096 Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2097 + " ViewId=" + av.getViewId()
2098 + " 's alignment is NULL! returning immediately.");
2101 sgroup = seqsel.intersect(av.getAlignment(),
2102 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2103 if ((sgroup != null && sgroup.getSize() > 0))
2108 if (sgroup != null && sgroup.getSize() > 0)
2110 av.setSelectionGroup(sgroup);
2114 av.setSelectionGroup(null);
2116 av.isSelectionGroupChanged(true);
2121 // the current selection is unset or from a previous message
2122 // so import the new colsel.
2123 if (colsel == null || colsel.isEmpty())
2125 if (av.getColumnSelection() != null)
2127 av.getColumnSelection().clear();
2133 // TODO: shift colSel according to the intersecting sequences
2134 if (av.getColumnSelection() == null)
2136 av.setColumnSelection(new ColumnSelection(colsel));
2140 av.getColumnSelection().setElementsFrom(colsel,
2141 av.getAlignment().getHiddenColumns());
2144 av.isColSelChanged(true);
2149 && av.hasHiddenColumns()
2150 && (av.getAlignment().getHiddenColumns() == null))
2152 System.err.println("Bad things");
2154 if (repaint) // always true!
2156 // probably finessing with multiple redraws here
2157 PaintRefresher.Refresh(this, av.getSequenceSetId());
2158 // ap.paintAlignment(false);
2161 // lastly, update dependent dialogs
2162 if (ap.getCalculationDialog() != null)
2164 ap.getCalculationDialog().validateCalcTypes();
2170 * If this panel is a cdna/protein translation view of the selection source,
2171 * tries to map the source selection to a local one, and returns true. Else
2178 protected boolean selectionFromTranslation(SequenceGroup seqsel,
2179 ColumnSelection colsel, HiddenColumns hidden,
2180 SelectionSource source)
2182 if (!(source instanceof AlignViewportI))
2186 final AlignViewportI sourceAv = (AlignViewportI) source;
2187 if (sourceAv.getCodingComplement() != av
2188 && av.getCodingComplement() != sourceAv)
2194 * Map sequence selection
2196 SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2197 av.setSelectionGroup(sg);
2198 av.isSelectionGroupChanged(true);
2201 * Map column selection
2203 // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2205 ColumnSelection cs = new ColumnSelection();
2206 HiddenColumns hs = new HiddenColumns();
2207 MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2208 av.setColumnSelection(cs);
2209 av.getAlignment().setHiddenColumns(hs);
2211 // lastly, update any dependent dialogs
2212 if (ap.getCalculationDialog() != null)
2214 ap.getCalculationDialog().validateCalcTypes();
2217 PaintRefresher.Refresh(this, av.getSequenceSetId());