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;
89 * last column position for mouseMoved event
91 private int lastMouseColumn;
94 * last sequence offset for mouseMoved event
96 private int lastMouseSeq;
98 protected int lastres;
100 protected int startseq;
102 protected AlignViewport av;
104 ScrollThread scrollThread = null;
106 boolean mouseDragging = false;
108 boolean editingSeqs = false;
110 boolean groupEditing = false;
112 // ////////////////////////////////////////
113 // ///Everything below this is for defining the boundary of the rubberband
114 // ////////////////////////////////////////
117 boolean changeEndSeq = false;
119 boolean changeStartSeq = false;
121 boolean changeEndRes = false;
123 boolean changeStartRes = false;
125 SequenceGroup stretchGroup = null;
127 boolean remove = false;
129 Point lastMousePress;
131 boolean mouseWheelPressed = false;
133 StringBuffer keyboardNo1;
135 StringBuffer keyboardNo2;
137 java.net.URL linkImageURL;
139 private final SequenceAnnotationReport seqARep;
141 StringBuilder tooltipText = new StringBuilder();
145 EditCommand editCommand;
147 StructureSelectionManager ssm;
149 SearchResultsI lastSearchResults;
152 * Creates a new SeqPanel object.
159 public SeqPanel(AlignViewport av, AlignmentPanel ap)
161 linkImageURL = getClass().getResource("/images/link.gif");
162 seqARep = new SequenceAnnotationReport(linkImageURL.toString());
163 ToolTipManager.sharedInstance().registerComponent(this);
164 ToolTipManager.sharedInstance().setInitialDelay(0);
165 ToolTipManager.sharedInstance().setDismissDelay(10000);
167 setBackground(Color.white);
169 seqCanvas = new SeqCanvas(ap);
170 setLayout(new BorderLayout());
171 add(seqCanvas, BorderLayout.CENTER);
177 addMouseMotionListener(this);
178 addMouseListener(this);
179 addMouseWheelListener(this);
180 ssm = av.getStructureSelectionManager();
181 ssm.addStructureViewerListener(this);
182 ssm.addSelectionListener(this);
185 lastMouseColumn = -1;
189 int startWrapBlock = -1;
191 int wrappedBlock = -1;
194 * Returns the aligned sequence position (base 0) at the mouse position, or
195 * the closest visible one
200 int findColumn(MouseEvent evt)
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();
219 x -= seqCanvas.LABEL_WEST;
221 int cwidth = seqCanvas.getWrappedCanvasWidth(this.getWidth());
227 wrappedBlock = y / cHeight;
228 wrappedBlock += av.getRanges().getStartRes() / cwidth;
230 res = wrappedBlock * cwidth + x / av.getCharWidth();
235 if (x > seqCanvas.getX() + seqCanvas.getWidth())
237 // make sure we calculate relative to visible alignment, rather than
239 x = seqCanvas.getX() + seqCanvas.getWidth();
241 res = (x / av.getCharWidth()) + av.getRanges().getStartRes();
242 if (res > av.getRanges().getEndRes())
245 res = av.getRanges().getEndRes();
249 if (av.hasHiddenColumns())
251 res = av.getAlignment().getHiddenColumns()
252 .adjustForHiddenColumns(res);
259 int findSeq(MouseEvent evt)
264 if (av.getWrapAlignment())
266 int hgap = av.getCharHeight();
267 if (av.getScaleAboveWrapped())
269 hgap += av.getCharHeight();
272 int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
273 + hgap + seqCanvas.getAnnotationHeight();
277 seq = Math.min((y % cHeight) / av.getCharHeight(), av.getAlignment()
282 seq = Math.min((y / av.getCharHeight())
283 + av.getRanges().getStartSeq(),
285 .getAlignment().getHeight() - 1);
292 * When all of a sequence of edits are complete, put the resulting edit list
293 * on the history stack (undo list), and reset flags for editing in progress.
299 if (editCommand != null && editCommand.getSize() > 0)
301 ap.alignFrame.addHistoryItem(editCommand);
302 av.firePropertyChange("alignment", null, av.getAlignment()
308 * Tidy up come what may...
313 groupEditing = false;
322 seqCanvas.cursorY = getKeyboardNo1() - 1;
326 void setCursorColumn()
328 seqCanvas.cursorX = getKeyboardNo1() - 1;
332 void setCursorRowAndColumn()
334 if (keyboardNo2 == null)
336 keyboardNo2 = new StringBuffer();
340 seqCanvas.cursorX = getKeyboardNo1() - 1;
341 seqCanvas.cursorY = getKeyboardNo2() - 1;
346 void setCursorPosition()
348 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
350 seqCanvas.cursorX = sequence.findIndex(getKeyboardNo1()) - 1;
354 void moveCursor(int dx, int dy)
356 seqCanvas.cursorX += dx;
357 seqCanvas.cursorY += dy;
359 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
361 if (av.hasHiddenColumns()
362 && !hidden.isVisible(seqCanvas.cursorX))
364 int original = seqCanvas.cursorX - dx;
365 int maxWidth = av.getAlignment().getWidth();
367 while (!hidden.isVisible(seqCanvas.cursorX)
368 && seqCanvas.cursorX < maxWidth && seqCanvas.cursorX > 0)
370 seqCanvas.cursorX += dx;
373 if (seqCanvas.cursorX >= maxWidth
374 || !hidden.isVisible(seqCanvas.cursorX))
376 seqCanvas.cursorX = original;
383 void scrollToVisible()
385 if (seqCanvas.cursorX < 0)
387 seqCanvas.cursorX = 0;
389 else if (seqCanvas.cursorX > av.getAlignment().getWidth() - 1)
391 seqCanvas.cursorX = av.getAlignment().getWidth() - 1;
394 if (seqCanvas.cursorY < 0)
396 seqCanvas.cursorY = 0;
398 else if (seqCanvas.cursorY > av.getAlignment().getHeight() - 1)
400 seqCanvas.cursorY = av.getAlignment().getHeight() - 1;
404 if (av.getWrapAlignment())
406 av.getRanges().scrollToWrappedVisible(seqCanvas.cursorX);
410 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 if (av.isFollowHighlight())
688 // don't allow highlight of protein/cDNA to also scroll a complementary
689 // panel,as this sets up a feedback loop (scrolling panel 1 causes moused
690 // over residue to change abruptly, causing highlighted residue in panel 2
691 // to change, causing a scroll in panel 1 etc)
692 ap.setToScrollComplementPanel(false);
693 if (ap.scrollToPosition(results, false))
695 seqCanvas.revalidate();
697 ap.setToScrollComplementPanel(true);
699 setStatusMessage(results);
700 seqCanvas.highlightSearchResults(results);
704 public VamsasSource getVamsasSource()
706 return this.ap == null ? null : this.ap.av;
710 public void updateColours(SequenceI seq, int index)
712 System.out.println("update the seqPanel colours");
723 public void mouseMoved(MouseEvent evt)
727 // This is because MacOSX creates a mouseMoved
728 // If control is down, other platforms will not.
732 final int column = findColumn(evt);
733 int seq = findSeq(evt);
734 if (column < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
738 if (column == lastMouseColumn && seq == lastMouseSeq)
741 * just a pixel move without change of residue
745 lastMouseColumn = column;
748 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
750 if (column >= sequence.getLength())
756 * set status bar message, returning residue position in sequence
758 boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
759 final int pos = setStatusMessage(sequence, column, seq);
760 if (ssm != null && !isGapped)
762 mouseOverSequence(sequence, column, pos);
765 tooltipText.setLength(6); // Cuts the buffer back to <html>
767 SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
770 for (int g = 0; g < groups.length; g++)
772 if (groups[g].getStartRes() <= column
773 && groups[g].getEndRes() >= column)
775 if (!groups[g].getName().startsWith("JTreeGroup")
776 && !groups[g].getName().startsWith("JGroup"))
778 tooltipText.append(groups[g].getName());
781 if (groups[g].getDescription() != null)
783 tooltipText.append(": " + groups[g].getDescription());
790 * add any features at the position to the tooltip; if over a gap, only
791 * add features that straddle the gap (pos may be the residue before or
794 if (av.isShowSequenceFeatures())
796 List<SequenceFeature> features = ap.getFeatureRenderer()
797 .findFeaturesAtRes(sequence.getDatasetSequence(), pos);
800 removeAdjacentFeatures(features, column + 1, sequence);
802 seqARep.appendFeatures(tooltipText, pos, features,
803 this.ap.getSeqPanel().seqCanvas.fr.getMinMax());
805 if (tooltipText.length() == 6) // <html>
807 setToolTipText(null);
812 String textString = tooltipText.toString();
813 if (lastTooltip == null || !lastTooltip.equals(textString))
815 String formattedTooltipText = JvSwingUtils.wrapTooltip(true,
817 setToolTipText(formattedTooltipText);
818 lastTooltip = textString;
824 * Removes from the list of features any that start after, or end before, the
825 * given column position. This allows us to retain only those features
826 * adjacent to a gapped position that straddle the position. Contact features
827 * that 'straddle' the position are also removed, since they are not 'at' the
832 * alignment column (1..)
835 protected void removeAdjacentFeatures(List<SequenceFeature> features,
836 final int column, SequenceI sequence)
838 // TODO should this be an AlignViewController method (and reused by applet)?
839 ListIterator<SequenceFeature> it = features.listIterator();
842 SequenceFeature sf = it.next();
843 if (sf.isContactFeature()
844 || sequence.findIndex(sf.getBegin()) > column
845 || sequence.findIndex(sf.getEnd()) < column)
852 private Point lastp = null;
857 * @see javax.swing.JComponent#getToolTipLocation(java.awt.event.MouseEvent)
860 public Point getToolTipLocation(MouseEvent event)
862 int x = event.getX(), w = getWidth();
863 int wdth = (w - x < 200) ? -(w / 2) : 5; // switch sides when tooltip is too
866 if (!event.isShiftDown() || p == null)
868 p = (tooltipText != null && tooltipText.length() > 6) ? new Point(
869 event.getX() + wdth, event.getY() - 20) : null;
872 * TODO: try to modify position region is not obcured by tooltip
880 * set when the current UI interaction has resulted in a change that requires
881 * overview shading to be recalculated. this could be changed to something
882 * more expressive that indicates what actually has changed, so selective
883 * redraws can be applied
885 private boolean needOverviewUpdate = false; // TODO: refactor to avcontroller
888 * set if av.getSelectionGroup() refers to a group that is defined on the
889 * alignment view, rather than a transient selection
891 // private boolean editingDefinedGroup = false; // TODO: refactor to
892 // avcontroller or viewModel
895 * Sets the status message in alignment panel, showing the sequence number
896 * (index) and id, and residue and residue position if not at a gap, for the
897 * given sequence and column position. Returns the residue position returned
898 * by Sequence.findPosition. Note this may be for the nearest adjacent residue
899 * if at a gapped position.
902 * aligned sequence object
906 * index of sequence in alignment
907 * @return sequence position of residue at column, or adjacent residue if at a
910 int setStatusMessage(SequenceI sequence, final int column, int seq)
912 StringBuilder text = new StringBuilder(32);
915 * Sequence number (if known), and sequence name.
917 String seqno = seq == -1 ? "" : " " + (seq + 1);
918 text.append("Sequence").append(seqno).append(" ID: ")
919 .append(sequence.getName());
921 String residue = null;
924 * Try to translate the display character to residue name (null for gap).
926 final String displayChar = String.valueOf(sequence.getCharAt(column));
927 boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
928 int pos = sequence.findPosition(column);
932 boolean nucleotide = av.getAlignment().isNucleotide();
935 residue = ResidueProperties.nucleotideName.get(displayChar);
939 residue = "X".equalsIgnoreCase(displayChar) ? "X" : ("*"
940 .equals(displayChar) ? "STOP"
941 : ResidueProperties.aa2Triplet.get(displayChar));
943 text.append(" ").append(nucleotide ? "Nucleotide" : "Residue")
944 .append(": ").append(residue == null ? displayChar : residue);
946 text.append(" (").append(Integer.toString(pos)).append(")");
948 ap.alignFrame.statusBar.setText(text.toString());
954 * Set the status bar message to highlight the first matched position in
959 private void setStatusMessage(SearchResultsI results)
961 AlignmentI al = this.av.getAlignment();
962 int sequenceIndex = al.findIndex(results);
963 if (sequenceIndex == -1)
967 SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
968 for (SearchResultMatchI m : results.getResults())
970 SequenceI seq = m.getSequence();
971 if (seq.getDatasetSequence() != null)
973 seq = seq.getDatasetSequence();
979 * Convert position in sequence (base 1) to sequence character array
982 int start = m.getStart() - m.getSequence().getStart();
983 setStatusMessage(seq, start, sequenceIndex);
993 public void mouseDragged(MouseEvent evt)
995 if (mouseWheelPressed)
997 boolean inSplitFrame = ap.av.getCodingComplement() != null;
998 boolean copyChanges = inSplitFrame && av.isProteinFontAsCdna();
1000 int oldWidth = av.getCharWidth();
1002 // Which is bigger, left-right or up-down?
1003 if (Math.abs(evt.getY() - lastMousePress.getY()) > Math.abs(evt
1004 .getX() - lastMousePress.getX()))
1007 * on drag up or down, decrement or increment font size
1009 int fontSize = av.font.getSize();
1010 boolean fontChanged = false;
1012 if (evt.getY() < lastMousePress.getY())
1017 else if (evt.getY() > lastMousePress.getY())
1030 Font newFont = new Font(av.font.getName(), av.font.getStyle(),
1032 av.setFont(newFont, true);
1033 av.setCharWidth(oldWidth);
1037 ap.av.getCodingComplement().setFont(newFont, true);
1038 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1039 .getSplitViewContainer();
1040 splitFrame.adjustLayout();
1041 splitFrame.repaint();
1048 * on drag left or right, decrement or increment character width
1051 if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
1053 newWidth = av.getCharWidth() - 1;
1054 av.setCharWidth(newWidth);
1056 else if (evt.getX() > lastMousePress.getX())
1058 newWidth = av.getCharWidth() + 1;
1059 av.setCharWidth(newWidth);
1063 ap.paintAlignment(false);
1067 * need to ensure newWidth is set on cdna, regardless of which
1068 * panel the mouse drag happened in; protein will compute its
1069 * character width as 1:1 or 3:1
1071 av.getCodingComplement().setCharWidth(newWidth);
1072 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1073 .getSplitViewContainer();
1074 splitFrame.adjustLayout();
1075 splitFrame.repaint();
1080 FontMetrics fm = getFontMetrics(av.getFont());
1081 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1083 lastMousePress = evt.getPoint();
1090 doMouseDraggedDefineMode(evt);
1094 int res = findColumn(evt);
1101 if ((lastres == -1) || (lastres == res))
1106 if ((res < av.getAlignment().getWidth()) && (res < lastres))
1108 // dragLeft, delete gap
1109 editSequence(false, false, res);
1113 editSequence(true, false, res);
1116 mouseDragging = true;
1117 if (scrollThread != null)
1119 scrollThread.setEvent(evt);
1123 // TODO: Make it more clever than many booleans
1124 synchronized void editSequence(boolean insertGap, boolean editSeq,
1128 int fixedRight = -1;
1129 boolean fixedColumns = false;
1130 SequenceGroup sg = av.getSelectionGroup();
1132 SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1134 // No group, but the sequence may represent a group
1135 if (!groupEditing && av.hasHiddenRows())
1137 if (av.isHiddenRepSequence(seq))
1139 sg = av.getRepresentedSequences(seq);
1140 groupEditing = true;
1144 StringBuilder message = new StringBuilder(64);
1147 message.append("Edit group:");
1148 if (editCommand == null)
1150 editCommand = new EditCommand(
1151 MessageManager.getString("action.edit_group"));
1156 message.append("Edit sequence: " + seq.getName());
1157 String label = seq.getName();
1158 if (label.length() > 10)
1160 label = label.substring(0, 10);
1162 if (editCommand == null)
1164 editCommand = new EditCommand(MessageManager.formatMessage(
1165 "label.edit_params", new String[] { label }));
1171 message.append(" insert ");
1175 message.append(" delete ");
1178 message.append(Math.abs(startres - lastres) + " gaps.");
1179 ap.alignFrame.statusBar.setText(message.toString());
1181 // Are we editing within a selection group?
1183 || (sg != null && sg.getSequences(av.getHiddenRepSequences())
1186 fixedColumns = true;
1188 // sg might be null as the user may only see 1 sequence,
1189 // but the sequence represents a group
1192 if (!av.isHiddenRepSequence(seq))
1197 sg = av.getRepresentedSequences(seq);
1200 fixedLeft = sg.getStartRes();
1201 fixedRight = sg.getEndRes();
1203 if ((startres < fixedLeft && lastres >= fixedLeft)
1204 || (startres >= fixedLeft && lastres < fixedLeft)
1205 || (startres > fixedRight && lastres <= fixedRight)
1206 || (startres <= fixedRight && lastres > fixedRight))
1212 if (fixedLeft > startres)
1214 fixedRight = fixedLeft - 1;
1217 else if (fixedRight < startres)
1219 fixedLeft = fixedRight;
1224 if (av.hasHiddenColumns())
1226 fixedColumns = true;
1227 int y1 = av.getAlignment().getHiddenColumns()
1228 .getHiddenBoundaryLeft(startres);
1229 int y2 = av.getAlignment().getHiddenColumns()
1230 .getHiddenBoundaryRight(startres);
1232 if ((insertGap && startres > y1 && lastres < y1)
1233 || (!insertGap && startres < y2 && lastres > y2))
1239 // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1240 // Selection spans a hidden region
1241 if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1249 fixedRight = y2 - 1;
1256 List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1257 int g, groupSize = vseqs.size();
1258 SequenceI[] groupSeqs = new SequenceI[groupSize];
1259 for (g = 0; g < groupSeqs.length; g++)
1261 groupSeqs[g] = vseqs.get(g);
1267 // If the user has selected the whole sequence, and is dragging to
1268 // the right, we can still extend the alignment and selectionGroup
1269 if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1270 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1272 sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1273 fixedRight = sg.getEndRes();
1276 // Is it valid with fixed columns??
1277 // Find the next gap before the end
1278 // of the visible region boundary
1279 boolean blank = false;
1280 for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1284 for (g = 0; g < groupSize; g++)
1286 for (int j = 0; j < startres - lastres; j++)
1288 if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1303 if (sg.getSize() == av.getAlignment().getHeight())
1305 if ((av.hasHiddenColumns() && startres < av.getAlignment()
1306 .getHiddenColumns().getHiddenBoundaryRight(startres)))
1312 int alWidth = av.getAlignment().getWidth();
1313 if (av.hasHiddenRows())
1315 int hwidth = av.getAlignment().getHiddenSequences()
1317 if (hwidth > alWidth)
1322 // We can still insert gaps if the selectionGroup
1323 // contains all the sequences
1324 sg.setEndRes(sg.getEndRes() + startres - lastres);
1325 fixedRight = alWidth + startres - lastres;
1336 else if (!insertGap)
1338 // / Are we able to delete?
1339 // ie are all columns blank?
1341 for (g = 0; g < groupSize; g++)
1343 for (int j = startres; j < lastres; j++)
1345 if (groupSeqs[g].getLength() <= j)
1350 if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1352 // Not a gap, block edit not valid
1362 // dragging to the right
1363 if (fixedColumns && fixedRight != -1)
1365 for (int j = lastres; j < startres; j++)
1367 insertChar(j, groupSeqs, fixedRight);
1372 appendEdit(Action.INSERT_GAP, groupSeqs, startres, startres
1378 // dragging to the left
1379 if (fixedColumns && fixedRight != -1)
1381 for (int j = lastres; j > startres; j--)
1383 deleteChar(startres, groupSeqs, fixedRight);
1388 appendEdit(Action.DELETE_GAP, groupSeqs, startres, lastres
1395 // ///Editing a single sequence///////////
1399 // dragging to the right
1400 if (fixedColumns && fixedRight != -1)
1402 for (int j = lastres; j < startres; j++)
1404 insertChar(j, new SequenceI[] { seq }, fixedRight);
1409 appendEdit(Action.INSERT_GAP, new SequenceI[] { seq }, lastres,
1410 startres - lastres);
1417 // dragging to the left
1418 if (fixedColumns && fixedRight != -1)
1420 for (int j = lastres; j > startres; j--)
1422 if (!Comparison.isGap(seq.getCharAt(startres)))
1427 deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1432 // could be a keyboard edit trying to delete none gaps
1434 for (int m = startres; m < lastres; m++)
1436 if (!Comparison.isGap(seq.getCharAt(m)))
1445 appendEdit(Action.DELETE_GAP, new SequenceI[] { seq },
1451 {// insertGap==false AND editSeq==TRUE;
1452 if (fixedColumns && fixedRight != -1)
1454 for (int j = lastres; j < startres; j++)
1456 insertChar(j, new SequenceI[] { seq }, fixedRight);
1461 appendEdit(Action.INSERT_NUC, new SequenceI[] { seq }, lastres,
1462 startres - lastres);
1469 seqCanvas.repaint();
1472 void insertChar(int j, SequenceI[] seq, int fixedColumn)
1474 int blankColumn = fixedColumn;
1475 for (int s = 0; s < seq.length; s++)
1477 // Find the next gap before the end of the visible region boundary
1478 // If lastCol > j, theres a boundary after the gap insertion
1480 for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1482 if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1484 // Theres a space, so break and insert the gap
1489 if (blankColumn <= j)
1491 blankColumn = fixedColumn;
1497 appendEdit(Action.DELETE_GAP, seq, blankColumn, 1);
1499 appendEdit(Action.INSERT_GAP, seq, j, 1);
1504 * Helper method to add and perform one edit action.
1511 protected void appendEdit(Action action, SequenceI[] seq, int pos,
1515 final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1516 av.getAlignment().getGapCharacter());
1518 editCommand.appendEdit(edit, av.getAlignment(), true, null);
1521 void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1524 appendEdit(Action.DELETE_GAP, seq, j, 1);
1526 appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1);
1536 public void mouseEntered(MouseEvent e)
1543 if (scrollThread != null)
1545 scrollThread.running = false;
1546 scrollThread = null;
1557 public void mouseExited(MouseEvent e)
1559 if (av.getWrapAlignment())
1566 scrollThread = new ScrollThread();
1571 * Handler for double-click on a position with one or more sequence features.
1572 * Opens the Amend Features dialog to allow feature details to be amended, or
1573 * the feature deleted.
1576 public void mouseClicked(MouseEvent evt)
1578 SequenceGroup sg = null;
1579 SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
1580 if (evt.getClickCount() > 1)
1582 sg = av.getSelectionGroup();
1583 if (sg != null && sg.getSize() == 1
1584 && sg.getEndRes() - sg.getStartRes() < 2)
1586 av.setSelectionGroup(null);
1589 int column = findColumn(evt);
1590 boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
1593 * find features at the position (if not gapped), or straddling
1594 * the position (if at a gap)
1596 List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1597 .findFeaturesAtRes(sequence.getDatasetSequence(),
1598 sequence.findPosition(column));
1601 removeAdjacentFeatures(features, column, sequence);
1604 if (!features.isEmpty())
1607 * highlight the first feature at the position on the alignment
1609 SearchResultsI highlight = new SearchResults();
1610 highlight.addResult(sequence, features.get(0).getBegin(), features
1612 seqCanvas.highlightSearchResults(highlight);
1615 * open the Amend Features dialog; clear highlighting afterwards,
1616 * whether changes were made or not
1618 List<SequenceI> seqs = Collections.singletonList(sequence);
1619 seqCanvas.getFeatureRenderer().amendFeatures(seqs, features, false,
1621 seqCanvas.highlightSearchResults(null);
1627 public void mouseWheelMoved(MouseWheelEvent e)
1630 if (e.getWheelRotation() > 0)
1632 if (e.isShiftDown())
1634 av.getRanges().scrollRight(true);
1639 av.getRanges().scrollUp(false);
1644 if (e.isShiftDown())
1646 av.getRanges().scrollRight(false);
1650 av.getRanges().scrollUp(true);
1653 // TODO Update tooltip for new position.
1662 public void doMousePressedDefineMode(MouseEvent evt)
1664 final int res = findColumn(evt);
1665 final int seq = findSeq(evt);
1667 needOverviewUpdate = false;
1669 startWrapBlock = wrappedBlock;
1671 if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1673 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
1674 .getString("label.cannot_edit_annotations_in_wrapped_view"),
1675 MessageManager.getString("label.wrapped_view_no_edit"),
1676 JvOptionPane.WARNING_MESSAGE);
1680 if (seq < 0 || res < 0)
1685 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1687 if ((sequence == null) || (res > sequence.getLength()))
1692 stretchGroup = av.getSelectionGroup();
1694 if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1696 stretchGroup = av.getAlignment().findGroup(sequence, res);
1697 if (stretchGroup != null)
1699 // only update the current selection if the popup menu has a group to
1701 av.setSelectionGroup(stretchGroup);
1705 if (evt.isPopupTrigger()) // Mac: mousePressed
1712 * defer right-mouse click handling to mouseReleased on Windows
1713 * (where isPopupTrigger() will answer true)
1714 * NB isRightMouseButton is also true for Cmd-click on Mac
1716 if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1723 seqCanvas.cursorX = findColumn(evt);
1724 seqCanvas.cursorY = findSeq(evt);
1725 seqCanvas.repaint();
1729 if (stretchGroup == null)
1731 // Only if left mouse button do we want to change group sizes
1733 // define a new group here
1734 SequenceGroup sg = new SequenceGroup();
1735 sg.setStartRes(res);
1737 sg.addSequence(sequence, false);
1738 av.setSelectionGroup(sg);
1741 if (av.getConservationSelected())
1743 SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1747 if (av.getAbovePIDThreshold())
1749 SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1752 // TODO: stretchGroup will always be not null. Is this a merge error ?
1753 if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1755 // Edit end res position of selected group
1756 changeEndRes = true;
1758 else if ((stretchGroup != null)
1759 && (stretchGroup.getStartRes() == res))
1761 // Edit end res position of selected group
1762 changeStartRes = true;
1764 stretchGroup.getWidth();
1767 seqCanvas.repaint();
1771 * Build and show a pop-up menu at the right-click mouse position
1777 void showPopupMenu(MouseEvent evt)
1779 final int res = findColumn(evt);
1780 final int seq = findSeq(evt);
1781 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1782 List<SequenceFeature> allFeatures = ap.getFeatureRenderer()
1783 .findFeaturesAtRes(sequence.getDatasetSequence(),
1784 sequence.findPosition(res));
1785 List<String> links = new ArrayList<>();
1786 for (SequenceFeature sf : allFeatures)
1788 if (sf.links != null)
1790 for (String link : sf.links)
1797 PopupMenu pop = new PopupMenu(ap, null, links);
1798 pop.show(this, evt.getX(), evt.getY());
1802 * Update the display after mouse up on a selection or group
1805 * mouse released event details
1807 * true if this event is happening after a mouse drag (rather than a
1810 public void doMouseReleasedDefineMode(MouseEvent evt, boolean afterDrag)
1812 if (stretchGroup == null)
1816 // always do this - annotation has own state
1817 // but defer colourscheme update until hidden sequences are passed in
1818 boolean vischange = stretchGroup.recalcConservation(true);
1819 needOverviewUpdate |= vischange && av.isSelectionDefinedGroup()
1821 if (stretchGroup.cs != null)
1823 stretchGroup.cs.alignmentChanged(stretchGroup,
1824 av.getHiddenRepSequences());
1826 ResidueShaderI groupColourScheme = stretchGroup.getGroupColourScheme();
1827 String name = stretchGroup.getName();
1828 if (stretchGroup.cs.conservationApplied())
1830 SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1832 if (stretchGroup.cs.getThreshold() > 0)
1834 SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1837 PaintRefresher.Refresh(this, av.getSequenceSetId());
1838 ap.paintAlignment(needOverviewUpdate);
1839 needOverviewUpdate = false;
1840 changeEndRes = false;
1841 changeStartRes = false;
1842 stretchGroup = null;
1852 public void doMouseDraggedDefineMode(MouseEvent evt)
1854 int res = findColumn(evt);
1855 int y = findSeq(evt);
1857 if (wrappedBlock != startWrapBlock)
1862 if (stretchGroup == null)
1867 if (res >= av.getAlignment().getWidth())
1869 res = av.getAlignment().getWidth() - 1;
1872 if (stretchGroup.getEndRes() == res)
1874 // Edit end res position of selected group
1875 changeEndRes = true;
1877 else if (stretchGroup.getStartRes() == res)
1879 // Edit start res position of selected group
1880 changeStartRes = true;
1883 if (res < av.getRanges().getStartRes())
1885 res = av.getRanges().getStartRes();
1890 if (res > (stretchGroup.getStartRes() - 1))
1892 stretchGroup.setEndRes(res);
1893 needOverviewUpdate |= av.isSelectionDefinedGroup();
1896 else if (changeStartRes)
1898 if (res < (stretchGroup.getEndRes() + 1))
1900 stretchGroup.setStartRes(res);
1901 needOverviewUpdate |= av.isSelectionDefinedGroup();
1905 int dragDirection = 0;
1911 else if (y < oldSeq)
1916 while ((y != oldSeq) && (oldSeq > -1)
1917 && (y < av.getAlignment().getHeight()))
1919 // This routine ensures we don't skip any sequences, as the
1920 // selection is quite slow.
1921 Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1923 oldSeq += dragDirection;
1930 Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1932 if (stretchGroup.getSequences(null).contains(nextSeq))
1934 stretchGroup.deleteSequence(seq, false);
1935 needOverviewUpdate |= av.isSelectionDefinedGroup();
1941 stretchGroup.addSequence(seq, false);
1944 stretchGroup.addSequence(nextSeq, false);
1945 needOverviewUpdate |= av.isSelectionDefinedGroup();
1954 mouseDragging = true;
1956 if (scrollThread != null)
1958 scrollThread.setEvent(evt);
1961 seqCanvas.repaint();
1964 void scrollCanvas(MouseEvent evt)
1968 if (scrollThread != null)
1970 scrollThread.running = false;
1971 scrollThread = null;
1973 mouseDragging = false;
1977 if (scrollThread == null)
1979 scrollThread = new ScrollThread();
1982 mouseDragging = true;
1983 scrollThread.setEvent(evt);
1988 // this class allows scrolling off the bottom of the visible alignment
1989 class ScrollThread extends Thread
1993 boolean running = false;
1995 public ScrollThread()
2000 public void setEvent(MouseEvent e)
2005 public void stopScrolling()
2019 if (mouseDragging && (evt.getY() < 0)
2020 && (av.getRanges().getStartSeq() > 0))
2022 running = av.getRanges().scrollUp(true);
2025 if (mouseDragging && (evt.getY() >= getHeight())
2026 && (av.getAlignment().getHeight() > av.getRanges()
2029 running = av.getRanges().scrollUp(false);
2032 if (mouseDragging && (evt.getX() < 0))
2034 running = av.getRanges().scrollRight(false);
2036 else if (mouseDragging && (evt.getX() >= getWidth()))
2038 running = av.getRanges().scrollRight(true);
2045 } catch (Exception ex)
2053 * modify current selection according to a received message.
2056 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
2057 HiddenColumns hidden, SelectionSource source)
2059 // TODO: fix this hack - source of messages is align viewport, but SeqPanel
2060 // handles selection messages...
2061 // TODO: extend config options to allow user to control if selections may be
2062 // shared between viewports.
2063 boolean iSentTheSelection = (av == source || (source instanceof AlignViewport && ((AlignmentViewport) source)
2064 .getSequenceSetId().equals(av.getSequenceSetId())));
2066 if (iSentTheSelection)
2068 // respond to our own event by updating dependent dialogs
2069 if (ap.getCalculationDialog() != null)
2071 ap.getCalculationDialog().validateCalcTypes();
2077 // process further ?
2078 if (!av.followSelection)
2084 * Ignore the selection if there is one of our own pending.
2086 if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
2092 * Check for selection in a view of which this one is a dna/protein
2095 if (selectionFromTranslation(seqsel, colsel, hidden, source))
2100 // do we want to thread this ? (contention with seqsel and colsel locks, I
2103 * only copy colsel if there is a real intersection between
2104 * sequence selection and this panel's alignment
2106 boolean repaint = false;
2107 boolean copycolsel = false;
2109 SequenceGroup sgroup = null;
2110 if (seqsel != null && seqsel.getSize() > 0)
2112 if (av.getAlignment() == null)
2114 Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2115 + " ViewId=" + av.getViewId()
2116 + " 's alignment is NULL! returning immediately.");
2119 sgroup = seqsel.intersect(av.getAlignment(),
2120 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2121 if ((sgroup != null && sgroup.getSize() > 0))
2126 if (sgroup != null && sgroup.getSize() > 0)
2128 av.setSelectionGroup(sgroup);
2132 av.setSelectionGroup(null);
2134 av.isSelectionGroupChanged(true);
2139 // the current selection is unset or from a previous message
2140 // so import the new colsel.
2141 if (colsel == null || colsel.isEmpty())
2143 if (av.getColumnSelection() != null)
2145 av.getColumnSelection().clear();
2151 // TODO: shift colSel according to the intersecting sequences
2152 if (av.getColumnSelection() == null)
2154 av.setColumnSelection(new ColumnSelection(colsel));
2158 av.getColumnSelection().setElementsFrom(colsel,
2159 av.getAlignment().getHiddenColumns());
2162 av.isColSelChanged(true);
2167 && av.hasHiddenColumns()
2168 && (av.getAlignment().getHiddenColumns() == null || av
2169 .getAlignment().getHiddenColumns().getHiddenRegions() == null))
2171 System.err.println("Bad things");
2173 if (repaint) // always true!
2175 // probably finessing with multiple redraws here
2176 PaintRefresher.Refresh(this, av.getSequenceSetId());
2177 // ap.paintAlignment(false);
2180 // lastly, update dependent dialogs
2181 if (ap.getCalculationDialog() != null)
2183 ap.getCalculationDialog().validateCalcTypes();
2189 * If this panel is a cdna/protein translation view of the selection source,
2190 * tries to map the source selection to a local one, and returns true. Else
2197 protected boolean selectionFromTranslation(SequenceGroup seqsel,
2198 ColumnSelection colsel, HiddenColumns hidden,
2199 SelectionSource source)
2201 if (!(source instanceof AlignViewportI))
2205 final AlignViewportI sourceAv = (AlignViewportI) source;
2206 if (sourceAv.getCodingComplement() != av
2207 && av.getCodingComplement() != sourceAv)
2213 * Map sequence selection
2215 SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2216 av.setSelectionGroup(sg);
2217 av.isSelectionGroupChanged(true);
2220 * Map column selection
2222 // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2224 ColumnSelection cs = new ColumnSelection();
2225 HiddenColumns hs = new HiddenColumns();
2226 MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2227 av.setColumnSelection(cs);
2228 av.getAlignment().setHiddenColumns(hs);
2230 // lastly, update any dependent dialogs
2231 if (ap.getCalculationDialog() != null)
2233 ap.getCalculationDialog().validateCalcTypes();
2236 PaintRefresher.Refresh(this, av.getSequenceSetId());