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;
66 import javax.swing.JPanel;
67 import javax.swing.SwingUtilities;
68 import javax.swing.ToolTipManager;
74 * @version $Revision: 1.130 $
76 public class SeqPanel extends JPanel implements MouseListener,
77 MouseMotionListener, MouseWheelListener, SequenceListener,
82 public SeqCanvas seqCanvas;
85 public AlignmentPanel ap;
88 * last column position for mouseMoved event
90 private int lastMouseColumn;
93 * last sequence offset for mouseMoved event
95 private int lastMouseSeq;
97 protected int lastres;
99 protected int startseq;
101 protected AlignViewport av;
103 ScrollThread scrollThread = null;
105 boolean mouseDragging = false;
107 boolean editingSeqs = false;
109 boolean groupEditing = false;
111 // ////////////////////////////////////////
112 // ///Everything below this is for defining the boundary of the rubberband
113 // ////////////////////////////////////////
116 boolean changeEndSeq = false;
118 boolean changeStartSeq = false;
120 boolean changeEndRes = false;
122 boolean changeStartRes = false;
124 SequenceGroup stretchGroup = null;
126 boolean remove = false;
128 Point lastMousePress;
130 boolean mouseWheelPressed = false;
132 StringBuffer keyboardNo1;
134 StringBuffer keyboardNo2;
136 java.net.URL linkImageURL;
138 private final SequenceAnnotationReport seqARep;
140 StringBuilder tooltipText = new StringBuilder();
144 EditCommand editCommand;
146 StructureSelectionManager ssm;
148 SearchResultsI lastSearchResults;
151 * Creates a new SeqPanel object.
158 public SeqPanel(AlignViewport av, AlignmentPanel ap)
160 linkImageURL = getClass().getResource("/images/link.gif");
161 seqARep = new SequenceAnnotationReport(linkImageURL.toString());
162 ToolTipManager.sharedInstance().registerComponent(this);
163 ToolTipManager.sharedInstance().setInitialDelay(0);
164 ToolTipManager.sharedInstance().setDismissDelay(10000);
166 setBackground(Color.white);
168 seqCanvas = new SeqCanvas(ap);
169 setLayout(new BorderLayout());
170 add(seqCanvas, BorderLayout.CENTER);
176 addMouseMotionListener(this);
177 addMouseListener(this);
178 addMouseWheelListener(this);
179 ssm = av.getStructureSelectionManager();
180 ssm.addStructureViewerListener(this);
181 ssm.addSelectionListener(this);
184 lastMouseColumn = -1;
188 int startWrapBlock = -1;
190 int wrappedBlock = -1;
193 * Returns the aligned sequence position (base 0) at the mouse position, or
194 * the closest visible one
199 int findColumn(MouseEvent evt)
204 int startRes = av.getRanges().getStartRes();
205 if (av.getWrapAlignment())
208 int hgap = av.getCharHeight();
209 if (av.getScaleAboveWrapped())
211 hgap += av.getCharHeight();
214 int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
215 + hgap + seqCanvas.getAnnotationHeight();
218 y = Math.max(0, y - hgap);
219 x = Math.max(0, x - seqCanvas.labelWidthWest);
221 int cwidth = seqCanvas.getWrappedCanvasWidth(this.getWidth());
227 wrappedBlock = y / cHeight;
228 wrappedBlock += startRes / cwidth;
229 // allow for wrapped view scrolled right (possible from Overview)
230 int startOffset = startRes % cwidth;
231 res = wrappedBlock * cwidth + startOffset
232 + +Math.min(cwidth - 1, x / av.getCharWidth());
236 if (x > seqCanvas.getX() + seqCanvas.getWidth())
238 // make sure we calculate relative to visible alignment, rather than
240 x = seqCanvas.getX() + seqCanvas.getWidth();
242 res = (x / av.getCharWidth()) + startRes;
243 if (res > av.getRanges().getEndRes())
246 res = av.getRanges().getEndRes();
250 if (av.hasHiddenColumns())
252 res = av.getAlignment().getHiddenColumns()
253 .adjustForHiddenColumns(res);
260 int findSeq(MouseEvent evt)
265 if (av.getWrapAlignment())
267 int hgap = av.getCharHeight();
268 if (av.getScaleAboveWrapped())
270 hgap += av.getCharHeight();
273 int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
274 + hgap + seqCanvas.getAnnotationHeight();
278 seq = Math.min((y % cHeight) / av.getCharHeight(), av.getAlignment()
283 seq = Math.min((y / av.getCharHeight())
284 + av.getRanges().getStartSeq(),
286 .getAlignment().getHeight() - 1);
293 * When all of a sequence of edits are complete, put the resulting edit list
294 * on the history stack (undo list), and reset flags for editing in progress.
300 if (editCommand != null && editCommand.getSize() > 0)
302 ap.alignFrame.addHistoryItem(editCommand);
303 av.firePropertyChange("alignment", null, av.getAlignment()
309 * Tidy up come what may...
314 groupEditing = false;
323 seqCanvas.cursorY = getKeyboardNo1() - 1;
327 void setCursorColumn()
329 seqCanvas.cursorX = getKeyboardNo1() - 1;
333 void setCursorRowAndColumn()
335 if (keyboardNo2 == null)
337 keyboardNo2 = new StringBuffer();
341 seqCanvas.cursorX = getKeyboardNo1() - 1;
342 seqCanvas.cursorY = getKeyboardNo2() - 1;
347 void setCursorPosition()
349 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
351 seqCanvas.cursorX = sequence.findIndex(getKeyboardNo1()) - 1;
355 void moveCursor(int dx, int dy)
357 seqCanvas.cursorX += dx;
358 seqCanvas.cursorY += dy;
360 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
362 if (av.hasHiddenColumns()
363 && !hidden.isVisible(seqCanvas.cursorX))
365 int original = seqCanvas.cursorX - dx;
366 int maxWidth = av.getAlignment().getWidth();
368 while (!hidden.isVisible(seqCanvas.cursorX)
369 && seqCanvas.cursorX < maxWidth && seqCanvas.cursorX > 0)
371 seqCanvas.cursorX += dx;
374 if (seqCanvas.cursorX >= maxWidth
375 || !hidden.isVisible(seqCanvas.cursorX))
377 seqCanvas.cursorX = original;
384 void scrollToVisible()
386 if (seqCanvas.cursorX < 0)
388 seqCanvas.cursorX = 0;
390 else if (seqCanvas.cursorX > av.getAlignment().getWidth() - 1)
392 seqCanvas.cursorX = av.getAlignment().getWidth() - 1;
395 if (seqCanvas.cursorY < 0)
397 seqCanvas.cursorY = 0;
399 else if (seqCanvas.cursorY > av.getAlignment().getHeight() - 1)
401 seqCanvas.cursorY = av.getAlignment().getHeight() - 1;
405 if (av.getWrapAlignment())
407 av.getRanges().scrollToWrappedVisible(seqCanvas.cursorX);
411 av.getRanges().scrollToVisible(seqCanvas.cursorX, seqCanvas.cursorY);
413 setStatusMessage(av.getAlignment().getSequenceAt(seqCanvas.cursorY),
414 seqCanvas.cursorX, seqCanvas.cursorY);
419 void setSelectionAreaAtCursor(boolean topLeft)
421 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
423 if (av.getSelectionGroup() != null)
425 SequenceGroup sg = av.getSelectionGroup();
426 // Find the top and bottom of this group
427 int min = av.getAlignment().getHeight(), max = 0;
428 for (int i = 0; i < sg.getSize(); i++)
430 int index = av.getAlignment().findIndex(sg.getSequenceAt(i));
445 sg.setStartRes(seqCanvas.cursorX);
446 if (sg.getEndRes() < seqCanvas.cursorX)
448 sg.setEndRes(seqCanvas.cursorX);
451 min = seqCanvas.cursorY;
455 sg.setEndRes(seqCanvas.cursorX);
456 if (sg.getStartRes() > seqCanvas.cursorX)
458 sg.setStartRes(seqCanvas.cursorX);
461 max = seqCanvas.cursorY + 1;
466 // Only the user can do this
467 av.setSelectionGroup(null);
471 // Now add any sequences between min and max
472 sg.getSequences(null).clear();
473 for (int i = min; i < max; i++)
475 sg.addSequence(av.getAlignment().getSequenceAt(i), false);
480 if (av.getSelectionGroup() == null)
482 SequenceGroup sg = new SequenceGroup();
483 sg.setStartRes(seqCanvas.cursorX);
484 sg.setEndRes(seqCanvas.cursorX);
485 sg.addSequence(sequence, false);
486 av.setSelectionGroup(sg);
489 ap.paintAlignment(false);
493 void insertGapAtCursor(boolean group)
495 groupEditing = group;
496 startseq = seqCanvas.cursorY;
497 lastres = seqCanvas.cursorX;
498 editSequence(true, false, seqCanvas.cursorX + getKeyboardNo1());
502 void deleteGapAtCursor(boolean group)
504 groupEditing = group;
505 startseq = seqCanvas.cursorY;
506 lastres = seqCanvas.cursorX + getKeyboardNo1();
507 editSequence(false, false, seqCanvas.cursorX);
511 void insertNucAtCursor(boolean group, String nuc)
513 // TODO not called - delete?
514 groupEditing = group;
515 startseq = seqCanvas.cursorY;
516 lastres = seqCanvas.cursorX;
517 editSequence(false, true, seqCanvas.cursorX + getKeyboardNo1());
521 void numberPressed(char value)
523 if (keyboardNo1 == null)
525 keyboardNo1 = new StringBuffer();
528 if (keyboardNo2 != null)
530 keyboardNo2.append(value);
534 keyboardNo1.append(value);
542 if (keyboardNo1 != null)
544 int value = Integer.parseInt(keyboardNo1.toString());
548 } catch (Exception x)
559 if (keyboardNo2 != null)
561 int value = Integer.parseInt(keyboardNo2.toString());
565 } catch (Exception x)
579 public void mouseReleased(MouseEvent evt)
581 boolean didDrag = mouseDragging; // did we come here after a drag
582 mouseDragging = false;
583 mouseWheelPressed = false;
585 if (evt.isPopupTrigger()) // Windows: mouseReleased
594 doMouseReleasedDefineMode(evt, didDrag);
608 public void mousePressed(MouseEvent evt)
610 lastMousePress = evt.getPoint();
612 if (SwingUtilities.isMiddleMouseButton(evt))
614 mouseWheelPressed = true;
618 boolean isControlDown = Platform.isControlDown(evt);
619 if (evt.isShiftDown() || isControlDown)
629 doMousePressedDefineMode(evt);
633 int seq = findSeq(evt);
634 int res = findColumn(evt);
636 if (seq < 0 || res < 0)
641 if ((seq < av.getAlignment().getHeight())
642 && (res < av.getAlignment().getSequenceAt(seq).getLength()))
659 public void mouseOverSequence(SequenceI sequence, int index, int pos)
661 String tmp = sequence.hashCode() + " " + index + " " + pos;
663 if (lastMessage == null || !lastMessage.equals(tmp))
665 // System.err.println("mouseOver Sequence: "+tmp);
666 ssm.mouseOverSequence(sequence, index, pos, av);
672 * Highlight the mapped region described by the search results object (unless
673 * unchanged). This supports highlight of protein while mousing over linked
674 * cDNA and vice versa. The status bar is also updated to show the location of
675 * the start of the highlighted region.
678 public void highlightSequence(SearchResultsI results)
680 if (results == null || results.equals(lastSearchResults))
684 lastSearchResults = results;
686 boolean wasScrolled = false;
688 if (av.isFollowHighlight())
690 // don't allow highlight of protein/cDNA to also scroll a complementary
691 // panel,as this sets up a feedback loop (scrolling panel 1 causes moused
692 // over residue to change abruptly, causing highlighted residue in panel 2
693 // to change, causing a scroll in panel 1 etc)
694 ap.setToScrollComplementPanel(false);
695 wasScrolled = ap.scrollToPosition(results, false);
698 seqCanvas.revalidate();
700 ap.setToScrollComplementPanel(true);
703 boolean noFastPaint = wasScrolled && av.getWrapAlignment();
704 if (seqCanvas.highlightSearchResults(results, noFastPaint))
706 setStatusMessage(results);
711 public VamsasSource getVamsasSource()
713 return this.ap == null ? null : this.ap.av;
717 public void updateColours(SequenceI seq, int index)
719 System.out.println("update the seqPanel colours");
730 public void mouseMoved(MouseEvent evt)
734 // This is because MacOSX creates a mouseMoved
735 // If control is down, other platforms will not.
739 final int column = findColumn(evt);
740 int seq = findSeq(evt);
741 if (column < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
746 if (column == lastMouseColumn && seq == lastMouseSeq)
749 * just a pixel move without change of residue
753 lastMouseColumn = column;
756 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
758 if (column >= sequence.getLength())
764 * set status bar message, returning residue position in sequence
766 boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
767 final int pos = setStatusMessage(sequence, column, seq);
768 if (ssm != null && !isGapped)
770 mouseOverSequence(sequence, column, pos);
773 tooltipText.setLength(6); // Cuts the buffer back to <html>
775 SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
778 for (int g = 0; g < groups.length; g++)
780 if (groups[g].getStartRes() <= column
781 && groups[g].getEndRes() >= column)
783 if (!groups[g].getName().startsWith("JTreeGroup")
784 && !groups[g].getName().startsWith("JGroup"))
786 tooltipText.append(groups[g].getName());
789 if (groups[g].getDescription() != null)
791 tooltipText.append(": " + groups[g].getDescription());
798 * add any features at the position to the tooltip; if over a gap, only
799 * add features that straddle the gap (pos may be the residue before or
802 if (av.isShowSequenceFeatures())
804 List<SequenceFeature> features = ap.getFeatureRenderer()
805 .findFeaturesAtColumn(sequence, column + 1);
806 seqARep.appendFeatures(tooltipText, pos, features,
807 this.ap.getSeqPanel().seqCanvas.fr.getMinMax());
809 if (tooltipText.length() == 6) // <html>
811 setToolTipText(null);
816 String textString = tooltipText.toString();
817 if (lastTooltip == null || !lastTooltip.equals(textString))
819 String formattedTooltipText = JvSwingUtils.wrapTooltip(true,
821 setToolTipText(formattedTooltipText);
822 lastTooltip = textString;
827 private Point lastp = null;
832 * @see javax.swing.JComponent#getToolTipLocation(java.awt.event.MouseEvent)
835 public Point getToolTipLocation(MouseEvent event)
837 int x = event.getX(), w = getWidth();
838 int wdth = (w - x < 200) ? -(w / 2) : 5; // switch sides when tooltip is too
841 if (!event.isShiftDown() || p == null)
843 p = (tooltipText != null && tooltipText.length() > 6) ? new Point(
844 event.getX() + wdth, event.getY() - 20) : null;
847 * TODO: try to modify position region is not obcured by tooltip
855 * set when the current UI interaction has resulted in a change that requires
856 * overview shading to be recalculated. this could be changed to something
857 * more expressive that indicates what actually has changed, so selective
858 * redraws can be applied
860 private boolean needOverviewUpdate = false; // TODO: refactor to avcontroller
863 * set if av.getSelectionGroup() refers to a group that is defined on the
864 * alignment view, rather than a transient selection
866 // private boolean editingDefinedGroup = false; // TODO: refactor to
867 // avcontroller or viewModel
870 * Sets the status message in alignment panel, showing the sequence number
871 * (index) and id, and residue and residue position if not at a gap, for the
872 * given sequence and column position. Returns the residue position returned
873 * by Sequence.findPosition. Note this may be for the nearest adjacent residue
874 * if at a gapped position.
877 * aligned sequence object
881 * index of sequence in alignment
882 * @return sequence position of residue at column, or adjacent residue if at a
885 int setStatusMessage(SequenceI sequence, final int column, int seqIndex)
887 char sequenceChar = sequence.getCharAt(column);
888 int pos = sequence.findPosition(column);
889 setStatusMessage(sequence, seqIndex, sequenceChar, pos);
895 * Builds the status message for the current cursor location and writes it to
896 * the status bar, for example
899 * Sequence 3 ID: FER1_SOLLC
900 * Sequence 5 ID: FER1_PEA Residue: THR (4)
901 * Sequence 5 ID: FER1_PEA Residue: B (3)
902 * Sequence 6 ID: O.niloticus.3 Nucleotide: Uracil (2)
907 * sequence position in the alignment (1..)
908 * @param sequenceChar
909 * the character under the cursor
911 * the sequence residue position (if not over a gap)
913 protected void setStatusMessage(SequenceI sequence, int seqIndex,
914 char sequenceChar, int residuePos)
916 StringBuilder text = new StringBuilder(32);
919 * Sequence number (if known), and sequence name.
921 String seqno = seqIndex == -1 ? "" : " " + (seqIndex + 1);
922 text.append("Sequence").append(seqno).append(" ID: ")
923 .append(sequence.getName());
925 String residue = null;
928 * Try to translate the display character to residue name (null for gap).
930 boolean isGapped = Comparison.isGap(sequenceChar);
934 boolean nucleotide = av.getAlignment().isNucleotide();
935 String displayChar = String.valueOf(sequenceChar);
938 residue = ResidueProperties.nucleotideName.get(displayChar);
942 residue = "X".equalsIgnoreCase(displayChar) ? "X" : ("*"
943 .equals(displayChar) ? "STOP"
944 : ResidueProperties.aa2Triplet.get(displayChar));
946 text.append(" ").append(nucleotide ? "Nucleotide" : "Residue")
947 .append(": ").append(residue == null ? displayChar : residue);
949 text.append(" (").append(Integer.toString(residuePos)).append(")");
951 ap.alignFrame.statusBar.setText(text.toString());
955 * Set the status bar message to highlight the first matched position in
960 private void setStatusMessage(SearchResultsI results)
962 AlignmentI al = this.av.getAlignment();
963 int sequenceIndex = al.findIndex(results);
964 if (sequenceIndex == -1)
968 SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
969 for (SearchResultMatchI m : results.getResults())
971 SequenceI seq = m.getSequence();
972 if (seq.getDatasetSequence() != null)
974 seq = seq.getDatasetSequence();
979 int start = m.getStart();
980 setStatusMessage(seq, sequenceIndex, seq.getCharAt(start - 1),
991 public void mouseDragged(MouseEvent evt)
993 if (mouseWheelPressed)
995 boolean inSplitFrame = ap.av.getCodingComplement() != null;
996 boolean copyChanges = inSplitFrame && av.isProteinFontAsCdna();
998 int oldWidth = av.getCharWidth();
1000 // Which is bigger, left-right or up-down?
1001 if (Math.abs(evt.getY() - lastMousePress.getY()) > Math.abs(evt
1002 .getX() - lastMousePress.getX()))
1005 * on drag up or down, decrement or increment font size
1007 int fontSize = av.font.getSize();
1008 boolean fontChanged = false;
1010 if (evt.getY() < lastMousePress.getY())
1015 else if (evt.getY() > lastMousePress.getY())
1028 Font newFont = new Font(av.font.getName(), av.font.getStyle(),
1030 av.setFont(newFont, true);
1031 av.setCharWidth(oldWidth);
1035 ap.av.getCodingComplement().setFont(newFont, true);
1036 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1037 .getSplitViewContainer();
1038 splitFrame.adjustLayout();
1039 splitFrame.repaint();
1046 * on drag left or right, decrement or increment character width
1049 if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
1051 newWidth = av.getCharWidth() - 1;
1052 av.setCharWidth(newWidth);
1054 else if (evt.getX() > lastMousePress.getX())
1056 newWidth = av.getCharWidth() + 1;
1057 av.setCharWidth(newWidth);
1061 ap.paintAlignment(false);
1065 * need to ensure newWidth is set on cdna, regardless of which
1066 * panel the mouse drag happened in; protein will compute its
1067 * character width as 1:1 or 3:1
1069 av.getCodingComplement().setCharWidth(newWidth);
1070 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1071 .getSplitViewContainer();
1072 splitFrame.adjustLayout();
1073 splitFrame.repaint();
1078 FontMetrics fm = getFontMetrics(av.getFont());
1079 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1081 lastMousePress = evt.getPoint();
1088 doMouseDraggedDefineMode(evt);
1092 int res = findColumn(evt);
1099 if ((lastres == -1) || (lastres == res))
1104 if ((res < av.getAlignment().getWidth()) && (res < lastres))
1106 // dragLeft, delete gap
1107 editSequence(false, false, res);
1111 editSequence(true, false, res);
1114 mouseDragging = true;
1115 if (scrollThread != null)
1117 scrollThread.setEvent(evt);
1121 // TODO: Make it more clever than many booleans
1122 synchronized void editSequence(boolean insertGap, boolean editSeq,
1126 int fixedRight = -1;
1127 boolean fixedColumns = false;
1128 SequenceGroup sg = av.getSelectionGroup();
1130 SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1132 // No group, but the sequence may represent a group
1133 if (!groupEditing && av.hasHiddenRows())
1135 if (av.isHiddenRepSequence(seq))
1137 sg = av.getRepresentedSequences(seq);
1138 groupEditing = true;
1142 StringBuilder message = new StringBuilder(64);
1145 message.append("Edit group:");
1146 if (editCommand == null)
1148 editCommand = new EditCommand(
1149 MessageManager.getString("action.edit_group"));
1154 message.append("Edit sequence: " + seq.getName());
1155 String label = seq.getName();
1156 if (label.length() > 10)
1158 label = label.substring(0, 10);
1160 if (editCommand == null)
1162 editCommand = new EditCommand(MessageManager.formatMessage(
1163 "label.edit_params", new String[] { label }));
1169 message.append(" insert ");
1173 message.append(" delete ");
1176 message.append(Math.abs(startres - lastres) + " gaps.");
1177 ap.alignFrame.statusBar.setText(message.toString());
1179 // Are we editing within a selection group?
1181 || (sg != null && sg.getSequences(av.getHiddenRepSequences())
1184 fixedColumns = true;
1186 // sg might be null as the user may only see 1 sequence,
1187 // but the sequence represents a group
1190 if (!av.isHiddenRepSequence(seq))
1195 sg = av.getRepresentedSequences(seq);
1198 fixedLeft = sg.getStartRes();
1199 fixedRight = sg.getEndRes();
1201 if ((startres < fixedLeft && lastres >= fixedLeft)
1202 || (startres >= fixedLeft && lastres < fixedLeft)
1203 || (startres > fixedRight && lastres <= fixedRight)
1204 || (startres <= fixedRight && lastres > fixedRight))
1210 if (fixedLeft > startres)
1212 fixedRight = fixedLeft - 1;
1215 else if (fixedRight < startres)
1217 fixedLeft = fixedRight;
1222 if (av.hasHiddenColumns())
1224 fixedColumns = true;
1225 int y1 = av.getAlignment().getHiddenColumns()
1226 .getHiddenBoundaryLeft(startres);
1227 int y2 = av.getAlignment().getHiddenColumns()
1228 .getHiddenBoundaryRight(startres);
1230 if ((insertGap && startres > y1 && lastres < y1)
1231 || (!insertGap && startres < y2 && lastres > y2))
1237 // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1238 // Selection spans a hidden region
1239 if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1247 fixedRight = y2 - 1;
1254 List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1255 int g, groupSize = vseqs.size();
1256 SequenceI[] groupSeqs = new SequenceI[groupSize];
1257 for (g = 0; g < groupSeqs.length; g++)
1259 groupSeqs[g] = vseqs.get(g);
1265 // If the user has selected the whole sequence, and is dragging to
1266 // the right, we can still extend the alignment and selectionGroup
1267 if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1268 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1270 sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1271 fixedRight = sg.getEndRes();
1274 // Is it valid with fixed columns??
1275 // Find the next gap before the end
1276 // of the visible region boundary
1277 boolean blank = false;
1278 for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1282 for (g = 0; g < groupSize; g++)
1284 for (int j = 0; j < startres - lastres; j++)
1286 if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1301 if (sg.getSize() == av.getAlignment().getHeight())
1303 if ((av.hasHiddenColumns() && startres < av.getAlignment()
1304 .getHiddenColumns().getHiddenBoundaryRight(startres)))
1310 int alWidth = av.getAlignment().getWidth();
1311 if (av.hasHiddenRows())
1313 int hwidth = av.getAlignment().getHiddenSequences()
1315 if (hwidth > alWidth)
1320 // We can still insert gaps if the selectionGroup
1321 // contains all the sequences
1322 sg.setEndRes(sg.getEndRes() + startres - lastres);
1323 fixedRight = alWidth + startres - lastres;
1334 else if (!insertGap)
1336 // / Are we able to delete?
1337 // ie are all columns blank?
1339 for (g = 0; g < groupSize; g++)
1341 for (int j = startres; j < lastres; j++)
1343 if (groupSeqs[g].getLength() <= j)
1348 if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1350 // Not a gap, block edit not valid
1360 // dragging to the right
1361 if (fixedColumns && fixedRight != -1)
1363 for (int j = lastres; j < startres; j++)
1365 insertChar(j, groupSeqs, fixedRight);
1370 appendEdit(Action.INSERT_GAP, groupSeqs, startres, startres
1376 // dragging to the left
1377 if (fixedColumns && fixedRight != -1)
1379 for (int j = lastres; j > startres; j--)
1381 deleteChar(startres, groupSeqs, fixedRight);
1386 appendEdit(Action.DELETE_GAP, groupSeqs, startres, lastres
1393 // ///Editing a single sequence///////////
1397 // dragging to the right
1398 if (fixedColumns && fixedRight != -1)
1400 for (int j = lastres; j < startres; j++)
1402 insertChar(j, new SequenceI[] { seq }, fixedRight);
1407 appendEdit(Action.INSERT_GAP, new SequenceI[] { seq }, lastres,
1408 startres - lastres);
1415 // dragging to the left
1416 if (fixedColumns && fixedRight != -1)
1418 for (int j = lastres; j > startres; j--)
1420 if (!Comparison.isGap(seq.getCharAt(startres)))
1425 deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1430 // could be a keyboard edit trying to delete none gaps
1432 for (int m = startres; m < lastres; m++)
1434 if (!Comparison.isGap(seq.getCharAt(m)))
1443 appendEdit(Action.DELETE_GAP, new SequenceI[] { seq },
1449 {// insertGap==false AND editSeq==TRUE;
1450 if (fixedColumns && fixedRight != -1)
1452 for (int j = lastres; j < startres; j++)
1454 insertChar(j, new SequenceI[] { seq }, fixedRight);
1459 appendEdit(Action.INSERT_NUC, new SequenceI[] { seq }, lastres,
1460 startres - lastres);
1467 seqCanvas.repaint();
1470 void insertChar(int j, SequenceI[] seq, int fixedColumn)
1472 int blankColumn = fixedColumn;
1473 for (int s = 0; s < seq.length; s++)
1475 // Find the next gap before the end of the visible region boundary
1476 // If lastCol > j, theres a boundary after the gap insertion
1478 for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1480 if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1482 // Theres a space, so break and insert the gap
1487 if (blankColumn <= j)
1489 blankColumn = fixedColumn;
1495 appendEdit(Action.DELETE_GAP, seq, blankColumn, 1);
1497 appendEdit(Action.INSERT_GAP, seq, j, 1);
1502 * Helper method to add and perform one edit action.
1509 protected void appendEdit(Action action, SequenceI[] seq, int pos,
1513 final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1514 av.getAlignment().getGapCharacter());
1516 editCommand.appendEdit(edit, av.getAlignment(), true, null);
1519 void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1522 appendEdit(Action.DELETE_GAP, seq, j, 1);
1524 appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1);
1534 public void mouseEntered(MouseEvent e)
1541 if (scrollThread != null)
1543 scrollThread.running = false;
1544 scrollThread = null;
1555 public void mouseExited(MouseEvent e)
1557 if (av.getWrapAlignment())
1564 scrollThread = new ScrollThread();
1569 * Handler for double-click on a position with one or more sequence features.
1570 * Opens the Amend Features dialog to allow feature details to be amended, or
1571 * the feature deleted.
1574 public void mouseClicked(MouseEvent evt)
1576 SequenceGroup sg = null;
1577 SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
1578 if (evt.getClickCount() > 1)
1580 sg = av.getSelectionGroup();
1581 if (sg != null && sg.getSize() == 1
1582 && sg.getEndRes() - sg.getStartRes() < 2)
1584 av.setSelectionGroup(null);
1587 int column = findColumn(evt);
1590 * find features at the position (if not gapped), or straddling
1591 * the position (if at a gap)
1593 List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1594 .findFeaturesAtColumn(sequence, column + 1);
1596 if (!features.isEmpty())
1599 * highlight the first feature at the position on the alignment
1601 SearchResultsI highlight = new SearchResults();
1602 highlight.addResult(sequence, features.get(0).getBegin(), features
1604 seqCanvas.highlightSearchResults(highlight, false);
1607 * open the Amend Features dialog; clear highlighting afterwards,
1608 * whether changes were made or not
1610 List<SequenceI> seqs = Collections.singletonList(sequence);
1611 seqCanvas.getFeatureRenderer().amendFeatures(seqs, features, false,
1613 av.setSearchResults(null); // clear highlighting
1614 seqCanvas.repaint(); // draw new/amended features
1620 public void mouseWheelMoved(MouseWheelEvent e)
1623 if (e.getWheelRotation() > 0)
1625 if (e.isShiftDown())
1627 av.getRanges().scrollRight(true);
1630 else if (!av.getWrapAlignment())
1632 av.getRanges().scrollUp(false);
1637 if (e.isShiftDown())
1639 av.getRanges().scrollRight(false);
1641 else if (!av.getWrapAlignment())
1643 av.getRanges().scrollUp(true);
1646 // TODO Update tooltip for new position.
1655 public void doMousePressedDefineMode(MouseEvent evt)
1657 final int res = findColumn(evt);
1658 final int seq = findSeq(evt);
1660 needOverviewUpdate = false;
1662 startWrapBlock = wrappedBlock;
1664 if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1666 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
1667 .getString("label.cannot_edit_annotations_in_wrapped_view"),
1668 MessageManager.getString("label.wrapped_view_no_edit"),
1669 JvOptionPane.WARNING_MESSAGE);
1673 if (seq < 0 || res < 0)
1678 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1680 if ((sequence == null) || (res > sequence.getLength()))
1685 stretchGroup = av.getSelectionGroup();
1687 if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1689 stretchGroup = av.getAlignment().findGroup(sequence, res);
1690 if (stretchGroup != null)
1692 // only update the current selection if the popup menu has a group to
1694 av.setSelectionGroup(stretchGroup);
1698 if (evt.isPopupTrigger()) // Mac: mousePressed
1705 * defer right-mouse click handling to mouseReleased on Windows
1706 * (where isPopupTrigger() will answer true)
1707 * NB isRightMouseButton is also true for Cmd-click on Mac
1709 if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1716 seqCanvas.cursorX = findColumn(evt);
1717 seqCanvas.cursorY = findSeq(evt);
1718 seqCanvas.repaint();
1722 if (stretchGroup == null)
1724 // Only if left mouse button do we want to change group sizes
1726 // define a new group here
1727 SequenceGroup sg = new SequenceGroup();
1728 sg.setStartRes(res);
1730 sg.addSequence(sequence, false);
1731 av.setSelectionGroup(sg);
1734 if (av.getConservationSelected())
1736 SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1740 if (av.getAbovePIDThreshold())
1742 SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1745 // TODO: stretchGroup will always be not null. Is this a merge error ?
1746 if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1748 // Edit end res position of selected group
1749 changeEndRes = true;
1751 else if ((stretchGroup != null)
1752 && (stretchGroup.getStartRes() == res))
1754 // Edit end res position of selected group
1755 changeStartRes = true;
1757 stretchGroup.getWidth();
1760 seqCanvas.repaint();
1764 * Build and show a pop-up menu at the right-click mouse position
1770 void showPopupMenu(MouseEvent evt)
1772 final int column = findColumn(evt);
1773 final int seq = findSeq(evt);
1774 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1775 List<SequenceFeature> allFeatures = ap.getFeatureRenderer()
1776 .findFeaturesAtColumn(sequence, column + 1);
1777 List<String> links = new ArrayList<>();
1778 for (SequenceFeature sf : allFeatures)
1780 if (sf.links != null)
1782 for (String link : sf.links)
1789 PopupMenu pop = new PopupMenu(ap, null, links);
1790 pop.show(this, evt.getX(), evt.getY());
1794 * Update the display after mouse up on a selection or group
1797 * mouse released event details
1799 * true if this event is happening after a mouse drag (rather than a
1802 public void doMouseReleasedDefineMode(MouseEvent evt, boolean afterDrag)
1804 if (stretchGroup == null)
1808 // always do this - annotation has own state
1809 // but defer colourscheme update until hidden sequences are passed in
1810 boolean vischange = stretchGroup.recalcConservation(true);
1811 needOverviewUpdate |= vischange && av.isSelectionDefinedGroup()
1813 if (stretchGroup.cs != null)
1815 stretchGroup.cs.alignmentChanged(stretchGroup,
1816 av.getHiddenRepSequences());
1818 ResidueShaderI groupColourScheme = stretchGroup.getGroupColourScheme();
1819 String name = stretchGroup.getName();
1820 if (stretchGroup.cs.conservationApplied())
1822 SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1824 if (stretchGroup.cs.getThreshold() > 0)
1826 SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1829 PaintRefresher.Refresh(this, av.getSequenceSetId());
1830 ap.paintAlignment(needOverviewUpdate);
1831 needOverviewUpdate = false;
1832 changeEndRes = false;
1833 changeStartRes = false;
1834 stretchGroup = null;
1844 public void doMouseDraggedDefineMode(MouseEvent evt)
1846 int res = findColumn(evt);
1847 int y = findSeq(evt);
1849 if (wrappedBlock != startWrapBlock)
1854 if (stretchGroup == null)
1859 if (res >= av.getAlignment().getWidth())
1861 res = av.getAlignment().getWidth() - 1;
1864 if (stretchGroup.getEndRes() == res)
1866 // Edit end res position of selected group
1867 changeEndRes = true;
1869 else if (stretchGroup.getStartRes() == res)
1871 // Edit start res position of selected group
1872 changeStartRes = true;
1875 if (res < av.getRanges().getStartRes())
1877 res = av.getRanges().getStartRes();
1882 if (res > (stretchGroup.getStartRes() - 1))
1884 stretchGroup.setEndRes(res);
1885 needOverviewUpdate |= av.isSelectionDefinedGroup();
1888 else if (changeStartRes)
1890 if (res < (stretchGroup.getEndRes() + 1))
1892 stretchGroup.setStartRes(res);
1893 needOverviewUpdate |= av.isSelectionDefinedGroup();
1897 int dragDirection = 0;
1903 else if (y < oldSeq)
1908 while ((y != oldSeq) && (oldSeq > -1)
1909 && (y < av.getAlignment().getHeight()))
1911 // This routine ensures we don't skip any sequences, as the
1912 // selection is quite slow.
1913 Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1915 oldSeq += dragDirection;
1922 Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1924 if (stretchGroup.getSequences(null).contains(nextSeq))
1926 stretchGroup.deleteSequence(seq, false);
1927 needOverviewUpdate |= av.isSelectionDefinedGroup();
1933 stretchGroup.addSequence(seq, false);
1936 stretchGroup.addSequence(nextSeq, false);
1937 needOverviewUpdate |= av.isSelectionDefinedGroup();
1946 mouseDragging = true;
1948 if (scrollThread != null)
1950 scrollThread.setEvent(evt);
1953 seqCanvas.repaint();
1956 void scrollCanvas(MouseEvent evt)
1960 if (scrollThread != null)
1962 scrollThread.running = false;
1963 scrollThread = null;
1965 mouseDragging = false;
1969 if (scrollThread == null)
1971 scrollThread = new ScrollThread();
1974 mouseDragging = true;
1975 scrollThread.setEvent(evt);
1980 // this class allows scrolling off the bottom of the visible alignment
1981 class ScrollThread extends Thread
1985 boolean running = false;
1987 public ScrollThread()
1992 public void setEvent(MouseEvent e)
1997 public void stopScrolling()
2011 if (mouseDragging && (evt.getY() < 0)
2012 && (av.getRanges().getStartSeq() > 0))
2014 running = av.getRanges().scrollUp(true);
2017 if (mouseDragging && (evt.getY() >= getHeight())
2018 && (av.getAlignment().getHeight() > av.getRanges()
2021 running = av.getRanges().scrollUp(false);
2024 if (mouseDragging && (evt.getX() < 0))
2026 running = av.getRanges().scrollRight(false);
2028 else if (mouseDragging && (evt.getX() >= getWidth()))
2030 running = av.getRanges().scrollRight(true);
2037 } catch (Exception ex)
2045 * modify current selection according to a received message.
2048 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
2049 HiddenColumns hidden, SelectionSource source)
2051 // TODO: fix this hack - source of messages is align viewport, but SeqPanel
2052 // handles selection messages...
2053 // TODO: extend config options to allow user to control if selections may be
2054 // shared between viewports.
2055 boolean iSentTheSelection = (av == source || (source instanceof AlignViewport && ((AlignmentViewport) source)
2056 .getSequenceSetId().equals(av.getSequenceSetId())));
2058 if (iSentTheSelection)
2060 // respond to our own event by updating dependent dialogs
2061 if (ap.getCalculationDialog() != null)
2063 ap.getCalculationDialog().validateCalcTypes();
2069 // process further ?
2070 if (!av.followSelection)
2076 * Ignore the selection if there is one of our own pending.
2078 if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
2084 * Check for selection in a view of which this one is a dna/protein
2087 if (selectionFromTranslation(seqsel, colsel, hidden, source))
2092 // do we want to thread this ? (contention with seqsel and colsel locks, I
2095 * only copy colsel if there is a real intersection between
2096 * sequence selection and this panel's alignment
2098 boolean repaint = false;
2099 boolean copycolsel = false;
2101 SequenceGroup sgroup = null;
2102 if (seqsel != null && seqsel.getSize() > 0)
2104 if (av.getAlignment() == null)
2106 Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2107 + " ViewId=" + av.getViewId()
2108 + " 's alignment is NULL! returning immediately.");
2111 sgroup = seqsel.intersect(av.getAlignment(),
2112 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2113 if ((sgroup != null && sgroup.getSize() > 0))
2118 if (sgroup != null && sgroup.getSize() > 0)
2120 av.setSelectionGroup(sgroup);
2124 av.setSelectionGroup(null);
2126 av.isSelectionGroupChanged(true);
2131 // the current selection is unset or from a previous message
2132 // so import the new colsel.
2133 if (colsel == null || colsel.isEmpty())
2135 if (av.getColumnSelection() != null)
2137 av.getColumnSelection().clear();
2143 // TODO: shift colSel according to the intersecting sequences
2144 if (av.getColumnSelection() == null)
2146 av.setColumnSelection(new ColumnSelection(colsel));
2150 av.getColumnSelection().setElementsFrom(colsel,
2151 av.getAlignment().getHiddenColumns());
2154 av.isColSelChanged(true);
2159 && av.hasHiddenColumns()
2160 && (av.getAlignment().getHiddenColumns() == null))
2162 System.err.println("Bad things");
2164 if (repaint) // always true!
2166 // probably finessing with multiple redraws here
2167 PaintRefresher.Refresh(this, av.getSequenceSetId());
2168 // ap.paintAlignment(false);
2171 // lastly, update dependent dialogs
2172 if (ap.getCalculationDialog() != null)
2174 ap.getCalculationDialog().validateCalcTypes();
2180 * If this panel is a cdna/protein translation view of the selection source,
2181 * tries to map the source selection to a local one, and returns true. Else
2188 protected boolean selectionFromTranslation(SequenceGroup seqsel,
2189 ColumnSelection colsel, HiddenColumns hidden,
2190 SelectionSource source)
2192 if (!(source instanceof AlignViewportI))
2196 final AlignViewportI sourceAv = (AlignViewportI) source;
2197 if (sourceAv.getCodingComplement() != av
2198 && av.getCodingComplement() != sourceAv)
2204 * Map sequence selection
2206 SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2207 av.setSelectionGroup(sg);
2208 av.isSelectionGroupChanged(true);
2211 * Map column selection
2213 // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2215 ColumnSelection cs = new ColumnSelection();
2216 HiddenColumns hs = new HiddenColumns();
2217 MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2218 av.setColumnSelection(cs);
2219 av.getAlignment().setHiddenColumns(hs);
2221 // lastly, update any dependent dialogs
2222 if (ap.getCalculationDialog() != null)
2224 ap.getCalculationDialog().validateCalcTypes();
2227 PaintRefresher.Refresh(this, av.getSequenceSetId());