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.SearchResultMatchI;
31 import jalview.datamodel.SearchResults;
32 import jalview.datamodel.SearchResultsI;
33 import jalview.datamodel.Sequence;
34 import jalview.datamodel.SequenceFeature;
35 import jalview.datamodel.SequenceGroup;
36 import jalview.datamodel.SequenceI;
37 import jalview.io.SequenceAnnotationReport;
38 import jalview.renderer.ResidueShaderI;
39 import jalview.schemes.ResidueProperties;
40 import jalview.structure.SelectionListener;
41 import jalview.structure.SelectionSource;
42 import jalview.structure.SequenceListener;
43 import jalview.structure.StructureSelectionManager;
44 import jalview.structure.VamsasSource;
45 import jalview.util.Comparison;
46 import jalview.util.MappingUtils;
47 import jalview.util.MessageManager;
48 import jalview.util.Platform;
49 import jalview.viewmodel.AlignmentViewport;
51 import java.awt.BorderLayout;
52 import java.awt.Color;
54 import java.awt.FontMetrics;
55 import java.awt.Point;
56 import java.awt.event.MouseEvent;
57 import java.awt.event.MouseListener;
58 import java.awt.event.MouseMotionListener;
59 import java.awt.event.MouseWheelEvent;
60 import java.awt.event.MouseWheelListener;
61 import java.util.ArrayList;
62 import java.util.Collections;
63 import java.util.List;
65 import javax.swing.JPanel;
66 import javax.swing.SwingUtilities;
67 import javax.swing.ToolTipManager;
73 * @version $Revision: 1.130 $
75 public class SeqPanel extends JPanel implements MouseListener,
76 MouseMotionListener, MouseWheelListener, SequenceListener,
81 public SeqCanvas seqCanvas;
84 public AlignmentPanel ap;
86 protected int lastres;
88 protected int startseq;
90 protected AlignViewport av;
92 ScrollThread scrollThread = null;
94 boolean mouseDragging = false;
96 boolean editingSeqs = false;
98 boolean groupEditing = false;
100 // ////////////////////////////////////////
101 // ///Everything below this is for defining the boundary of the rubberband
102 // ////////////////////////////////////////
105 boolean changeEndSeq = false;
107 boolean changeStartSeq = false;
109 boolean changeEndRes = false;
111 boolean changeStartRes = false;
113 SequenceGroup stretchGroup = null;
115 boolean remove = false;
117 Point lastMousePress;
119 boolean mouseWheelPressed = false;
121 StringBuffer keyboardNo1;
123 StringBuffer keyboardNo2;
125 java.net.URL linkImageURL;
127 private final SequenceAnnotationReport seqARep;
129 StringBuilder tooltipText = new StringBuilder();
133 EditCommand editCommand;
135 StructureSelectionManager ssm;
137 SearchResultsI lastSearchResults;
140 * Creates a new SeqPanel object.
147 public SeqPanel(AlignViewport av, AlignmentPanel ap)
149 linkImageURL = getClass().getResource("/images/link.gif");
150 seqARep = new SequenceAnnotationReport(linkImageURL.toString());
151 ToolTipManager.sharedInstance().registerComponent(this);
152 ToolTipManager.sharedInstance().setInitialDelay(0);
153 ToolTipManager.sharedInstance().setDismissDelay(10000);
155 setBackground(Color.white);
157 seqCanvas = new SeqCanvas(ap);
158 setLayout(new BorderLayout());
159 add(seqCanvas, BorderLayout.CENTER);
165 addMouseMotionListener(this);
166 addMouseListener(this);
167 addMouseWheelListener(this);
168 ssm = av.getStructureSelectionManager();
169 ssm.addStructureViewerListener(this);
170 ssm.addSelectionListener(this);
174 int startWrapBlock = -1;
176 int wrappedBlock = -1;
179 * Returns the aligned sequence position (base 0) at the mouse position, or
180 * the closest visible one
185 int findRes(MouseEvent evt)
190 if (av.getWrapAlignment())
193 int hgap = av.getCharHeight();
194 if (av.getScaleAboveWrapped())
196 hgap += av.getCharHeight();
199 int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
200 + hgap + seqCanvas.getAnnotationHeight();
204 x -= seqCanvas.LABEL_WEST;
206 int cwidth = seqCanvas.getWrappedCanvasWidth(this.getWidth());
212 wrappedBlock = y / cHeight;
213 wrappedBlock += av.getRanges().getStartRes() / cwidth;
215 res = wrappedBlock * cwidth + x / av.getCharWidth();
220 if (x > seqCanvas.getX() + seqCanvas.getWidth())
222 // make sure we calculate relative to visible alignment, rather than
224 x = seqCanvas.getX() + seqCanvas.getWidth();
226 res = (x / av.getCharWidth()) + av.getRanges().getStartRes();
227 if (res > av.getRanges().getEndRes())
230 res = av.getRanges().getEndRes();
234 if (av.hasHiddenColumns())
236 res = av.getColumnSelection().adjustForHiddenColumns(res);
243 int findSeq(MouseEvent evt)
248 if (av.getWrapAlignment())
250 int hgap = av.getCharHeight();
251 if (av.getScaleAboveWrapped())
253 hgap += av.getCharHeight();
256 int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
257 + hgap + seqCanvas.getAnnotationHeight();
261 seq = Math.min((y % cHeight) / av.getCharHeight(), av.getAlignment()
266 seq = Math.min((y / av.getCharHeight())
267 + av.getRanges().getStartSeq(),
269 .getAlignment().getHeight() - 1);
276 * When all of a sequence of edits are complete, put the resulting edit list
277 * on the history stack (undo list), and reset flags for editing in progress.
283 if (editCommand != null && editCommand.getSize() > 0)
285 ap.alignFrame.addHistoryItem(editCommand);
286 av.firePropertyChange("alignment", null, av.getAlignment()
292 * Tidy up come what may...
297 groupEditing = false;
306 seqCanvas.cursorY = getKeyboardNo1() - 1;
310 void setCursorColumn()
312 seqCanvas.cursorX = getKeyboardNo1() - 1;
316 void setCursorRowAndColumn()
318 if (keyboardNo2 == null)
320 keyboardNo2 = new StringBuffer();
324 seqCanvas.cursorX = getKeyboardNo1() - 1;
325 seqCanvas.cursorY = getKeyboardNo2() - 1;
330 void setCursorPosition()
332 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
334 seqCanvas.cursorX = sequence.findIndex(getKeyboardNo1()) - 1;
338 void moveCursor(int dx, int dy)
340 seqCanvas.cursorX += dx;
341 seqCanvas.cursorY += dy;
342 if (av.hasHiddenColumns()
343 && !av.getColumnSelection().isVisible(seqCanvas.cursorX))
345 int original = seqCanvas.cursorX - dx;
346 int maxWidth = av.getAlignment().getWidth();
348 while (!av.getColumnSelection().isVisible(seqCanvas.cursorX)
349 && seqCanvas.cursorX < maxWidth && seqCanvas.cursorX > 0)
351 seqCanvas.cursorX += dx;
354 if (seqCanvas.cursorX >= maxWidth
355 || !av.getColumnSelection().isVisible(seqCanvas.cursorX))
357 seqCanvas.cursorX = original;
364 void scrollToVisible()
366 if (seqCanvas.cursorX < 0)
368 seqCanvas.cursorX = 0;
370 else if (seqCanvas.cursorX > av.getAlignment().getWidth() - 1)
372 seqCanvas.cursorX = av.getAlignment().getWidth() - 1;
375 if (seqCanvas.cursorY < 0)
377 seqCanvas.cursorY = 0;
379 else if (seqCanvas.cursorY > av.getAlignment().getHeight() - 1)
381 seqCanvas.cursorY = av.getAlignment().getHeight() - 1;
385 if (av.getWrapAlignment())
387 ap.scrollToWrappedVisible(seqCanvas.cursorX);
391 while (seqCanvas.cursorY < av.getRanges().getStartSeq())
395 while (seqCanvas.cursorY + 1 > av.getRanges().getEndSeq())
399 if (!av.getWrapAlignment())
401 while (seqCanvas.cursorX < av.getColumnSelection()
402 .adjustForHiddenColumns(av.getRanges().getStartRes()))
404 if (!ap.scrollRight(false))
409 while (seqCanvas.cursorX > av.getColumnSelection()
410 .adjustForHiddenColumns(av.getRanges().getEndRes()))
412 if (!ap.scrollRight(true))
419 setStatusMessage(av.getAlignment().getSequenceAt(seqCanvas.cursorY),
420 seqCanvas.cursorX, seqCanvas.cursorY);
425 void setSelectionAreaAtCursor(boolean topLeft)
427 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
429 if (av.getSelectionGroup() != null)
431 SequenceGroup sg = av.getSelectionGroup();
432 // Find the top and bottom of this group
433 int min = av.getAlignment().getHeight(), max = 0;
434 for (int i = 0; i < sg.getSize(); i++)
436 int index = av.getAlignment().findIndex(sg.getSequenceAt(i));
451 sg.setStartRes(seqCanvas.cursorX);
452 if (sg.getEndRes() < seqCanvas.cursorX)
454 sg.setEndRes(seqCanvas.cursorX);
457 min = seqCanvas.cursorY;
461 sg.setEndRes(seqCanvas.cursorX);
462 if (sg.getStartRes() > seqCanvas.cursorX)
464 sg.setStartRes(seqCanvas.cursorX);
467 max = seqCanvas.cursorY + 1;
472 // Only the user can do this
473 av.setSelectionGroup(null);
477 // Now add any sequences between min and max
478 sg.getSequences(null).clear();
479 for (int i = min; i < max; i++)
481 sg.addSequence(av.getAlignment().getSequenceAt(i), false);
486 if (av.getSelectionGroup() == null)
488 SequenceGroup sg = new SequenceGroup();
489 sg.setStartRes(seqCanvas.cursorX);
490 sg.setEndRes(seqCanvas.cursorX);
491 sg.addSequence(sequence, false);
492 av.setSelectionGroup(sg);
495 ap.paintAlignment(false);
499 void insertGapAtCursor(boolean group)
501 groupEditing = group;
502 startseq = seqCanvas.cursorY;
503 lastres = seqCanvas.cursorX;
504 editSequence(true, false, seqCanvas.cursorX + getKeyboardNo1());
508 void deleteGapAtCursor(boolean group)
510 groupEditing = group;
511 startseq = seqCanvas.cursorY;
512 lastres = seqCanvas.cursorX + getKeyboardNo1();
513 editSequence(false, false, seqCanvas.cursorX);
517 void insertNucAtCursor(boolean group, String nuc)
519 // TODO not called - delete?
520 groupEditing = group;
521 startseq = seqCanvas.cursorY;
522 lastres = seqCanvas.cursorX;
523 editSequence(false, true, seqCanvas.cursorX + getKeyboardNo1());
527 void numberPressed(char value)
529 if (keyboardNo1 == null)
531 keyboardNo1 = new StringBuffer();
534 if (keyboardNo2 != null)
536 keyboardNo2.append(value);
540 keyboardNo1.append(value);
548 if (keyboardNo1 != null)
550 int value = Integer.parseInt(keyboardNo1.toString());
554 } catch (Exception x)
565 if (keyboardNo2 != null)
567 int value = Integer.parseInt(keyboardNo2.toString());
571 } catch (Exception x)
585 public void mouseReleased(MouseEvent evt)
587 mouseDragging = false;
588 mouseWheelPressed = false;
590 if (evt.isPopupTrigger()) // Windows: mouseReleased
599 doMouseReleasedDefineMode(evt);
613 public void mousePressed(MouseEvent evt)
615 lastMousePress = evt.getPoint();
617 if (SwingUtilities.isMiddleMouseButton(evt))
619 mouseWheelPressed = true;
623 boolean isControlDown = Platform.isControlDown(evt);
624 if (evt.isShiftDown() || isControlDown)
634 doMousePressedDefineMode(evt);
638 int seq = findSeq(evt);
639 int res = findRes(evt);
641 if (seq < 0 || res < 0)
646 if ((seq < av.getAlignment().getHeight())
647 && (res < av.getAlignment().getSequenceAt(seq).getLength()))
664 public void mouseOverSequence(SequenceI sequence, int index, int pos)
666 String tmp = sequence.hashCode() + " " + index + " " + pos;
668 if (lastMessage == null || !lastMessage.equals(tmp))
670 // System.err.println("mouseOver Sequence: "+tmp);
671 ssm.mouseOverSequence(sequence, index, pos, av);
677 * Highlight the mapped region described by the search results object (unless
678 * unchanged). This supports highlight of protein while mousing over linked
679 * cDNA and vice versa. The status bar is also updated to show the location of
680 * the start of the highlighted region.
683 public void highlightSequence(SearchResultsI results)
685 if (results == null || results.equals(lastSearchResults))
689 lastSearchResults = results;
691 if (av.isFollowHighlight())
694 * if scrollToPosition requires a scroll adjustment, this flag prevents
695 * another scroll event being propagated back to the originator
697 * @see AlignmentPanel#adjustmentValueChanged
699 ap.setDontScrollComplement(true);
700 if (ap.scrollToPosition(results, false))
702 seqCanvas.revalidate();
705 setStatusMessage(results);
706 seqCanvas.highlightSearchResults(results);
710 public VamsasSource getVamsasSource()
712 return this.ap == null ? null : this.ap.av;
716 public void updateColours(SequenceI seq, int index)
718 System.out.println("update the seqPanel colours");
729 public void mouseMoved(MouseEvent evt)
733 // This is because MacOSX creates a mouseMoved
734 // If control is down, other platforms will not.
738 int res = findRes(evt);
739 int seq = findSeq(evt);
741 if (res < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
746 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
748 if (res >= sequence.getLength())
753 pos = setStatusMessage(sequence, res, seq);
754 if (ssm != null && pos > -1)
756 mouseOverSequence(sequence, res, pos);
759 tooltipText.setLength(6); // Cuts the buffer back to <html>
761 SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
764 for (int g = 0; g < groups.length; g++)
766 if (groups[g].getStartRes() <= res && groups[g].getEndRes() >= res)
768 if (!groups[g].getName().startsWith("JTreeGroup")
769 && !groups[g].getName().startsWith("JGroup"))
771 tooltipText.append(groups[g].getName());
774 if (groups[g].getDescription() != null)
776 tooltipText.append(": " + groups[g].getDescription());
782 // use aa to see if the mouse pointer is on a
783 if (av.isShowSequenceFeatures())
786 List<SequenceFeature> features = ap.getFeatureRenderer()
787 .findFeaturesAtRes(sequence.getDatasetSequence(),
788 rpos = sequence.findPosition(res));
789 seqARep.appendFeatures(tooltipText, rpos, features,
790 this.ap.getSeqPanel().seqCanvas.fr.getMinMax());
792 if (tooltipText.length() == 6) // <html>
794 setToolTipText(null);
799 if (lastTooltip == null
800 || !lastTooltip.equals(tooltipText.toString()))
802 String formatedTooltipText = JvSwingUtils.wrapTooltip(true,
803 tooltipText.toString());
804 // String formatedTooltipText = tooltipText.toString();
805 setToolTipText(formatedTooltipText);
806 lastTooltip = tooltipText.toString();
813 private Point lastp = null;
818 * @see javax.swing.JComponent#getToolTipLocation(java.awt.event.MouseEvent)
821 public Point getToolTipLocation(MouseEvent event)
823 int x = event.getX(), w = getWidth();
824 int wdth = (w - x < 200) ? -(w / 2) : 5; // switch sides when tooltip is too
827 if (!event.isShiftDown() || p == null)
829 p = (tooltipText != null && tooltipText.length() > 6) ? new Point(
830 event.getX() + wdth, event.getY() - 20) : null;
833 * TODO: try to modify position region is not obcured by tooltip
841 * set when the current UI interaction has resulted in a change that requires
842 * overview shading to be recalculated. this could be changed to something
843 * more expressive that indicates what actually has changed, so selective
844 * redraws can be applied
846 private boolean needOverviewUpdate = false; // TODO: refactor to avcontroller
849 * set if av.getSelectionGroup() refers to a group that is defined on the
850 * alignment view, rather than a transient selection
852 // private boolean editingDefinedGroup = false; // TODO: refactor to
853 // avcontroller or viewModel
856 * Set status message in alignment panel
859 * aligned sequence object
863 * index of sequence in alignment
864 * @return position of res in sequence
866 int setStatusMessage(SequenceI sequence, int res, int seq)
868 StringBuilder text = new StringBuilder(32);
871 * Sequence number (if known), and sequence name.
873 String seqno = seq == -1 ? "" : " " + (seq + 1);
874 text.append("Sequence").append(seqno).append(" ID: ")
875 .append(sequence.getName());
877 String residue = null;
879 * Try to translate the display character to residue name (null for gap).
881 final String displayChar = String.valueOf(sequence.getCharAt(res));
882 if (av.getAlignment().isNucleotide())
884 residue = ResidueProperties.nucleotideName.get(displayChar);
887 text.append(" Nucleotide: ").append(residue);
892 residue = "X".equalsIgnoreCase(displayChar) ? "X" : ("*"
893 .equals(displayChar) ? "STOP" : ResidueProperties.aa2Triplet
897 text.append(" Residue: ").append(residue);
904 pos = sequence.findPosition(res);
905 text.append(" (").append(Integer.toString(pos)).append(")");
907 ap.alignFrame.statusBar.setText(text.toString());
912 * Set the status bar message to highlight the first matched position in
917 private void setStatusMessage(SearchResultsI results)
919 AlignmentI al = this.av.getAlignment();
920 int sequenceIndex = al.findIndex(results);
921 if (sequenceIndex == -1)
925 SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
926 for (SearchResultMatchI m : results.getResults())
928 SequenceI seq = m.getSequence();
929 if (seq.getDatasetSequence() != null)
931 seq = seq.getDatasetSequence();
937 * Convert position in sequence (base 1) to sequence character array
940 int start = m.getStart() - m.getSequence().getStart();
941 setStatusMessage(seq, start, sequenceIndex);
954 public void mouseDragged(MouseEvent evt)
956 if (mouseWheelPressed)
958 int oldWidth = av.getCharWidth();
960 // Which is bigger, left-right or up-down?
961 if (Math.abs(evt.getY() - lastMousePress.getY()) > Math.abs(evt
962 .getX() - lastMousePress.getX()))
964 int fontSize = av.font.getSize();
966 if (evt.getY() < lastMousePress.getY())
970 else if (evt.getY() > lastMousePress.getY())
981 new Font(av.font.getName(), av.font.getStyle(), fontSize),
983 av.setCharWidth(oldWidth);
988 if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
990 av.setCharWidth(av.getCharWidth() - 1);
992 else if (evt.getX() > lastMousePress.getX())
994 av.setCharWidth(av.getCharWidth() + 1);
997 ap.paintAlignment(false);
1000 FontMetrics fm = getFontMetrics(av.getFont());
1001 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1003 lastMousePress = evt.getPoint();
1010 doMouseDraggedDefineMode(evt);
1014 int res = findRes(evt);
1021 if ((lastres == -1) || (lastres == res))
1026 if ((res < av.getAlignment().getWidth()) && (res < lastres))
1028 // dragLeft, delete gap
1029 editSequence(false, false, res);
1033 editSequence(true, false, res);
1036 mouseDragging = true;
1037 if (scrollThread != null)
1039 scrollThread.setEvent(evt);
1043 // TODO: Make it more clever than many booleans
1044 synchronized void editSequence(boolean insertGap, boolean editSeq,
1048 int fixedRight = -1;
1049 boolean fixedColumns = false;
1050 SequenceGroup sg = av.getSelectionGroup();
1052 SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1054 // No group, but the sequence may represent a group
1055 if (!groupEditing && av.hasHiddenRows())
1057 if (av.isHiddenRepSequence(seq))
1059 sg = av.getRepresentedSequences(seq);
1060 groupEditing = true;
1064 StringBuilder message = new StringBuilder(64);
1067 message.append("Edit group:");
1068 if (editCommand == null)
1070 editCommand = new EditCommand(
1071 MessageManager.getString("action.edit_group"));
1076 message.append("Edit sequence: " + seq.getName());
1077 String label = seq.getName();
1078 if (label.length() > 10)
1080 label = label.substring(0, 10);
1082 if (editCommand == null)
1084 editCommand = new EditCommand(MessageManager.formatMessage(
1085 "label.edit_params", new String[] { label }));
1091 message.append(" insert ");
1095 message.append(" delete ");
1098 message.append(Math.abs(startres - lastres) + " gaps.");
1099 ap.alignFrame.statusBar.setText(message.toString());
1101 // Are we editing within a selection group?
1103 || (sg != null && sg.getSequences(av.getHiddenRepSequences())
1106 fixedColumns = true;
1108 // sg might be null as the user may only see 1 sequence,
1109 // but the sequence represents a group
1112 if (!av.isHiddenRepSequence(seq))
1117 sg = av.getRepresentedSequences(seq);
1120 fixedLeft = sg.getStartRes();
1121 fixedRight = sg.getEndRes();
1123 if ((startres < fixedLeft && lastres >= fixedLeft)
1124 || (startres >= fixedLeft && lastres < fixedLeft)
1125 || (startres > fixedRight && lastres <= fixedRight)
1126 || (startres <= fixedRight && lastres > fixedRight))
1132 if (fixedLeft > startres)
1134 fixedRight = fixedLeft - 1;
1137 else if (fixedRight < startres)
1139 fixedLeft = fixedRight;
1144 if (av.hasHiddenColumns())
1146 fixedColumns = true;
1147 int y1 = av.getColumnSelection().getHiddenBoundaryLeft(startres);
1148 int y2 = av.getColumnSelection().getHiddenBoundaryRight(startres);
1150 if ((insertGap && startres > y1 && lastres < y1)
1151 || (!insertGap && startres < y2 && lastres > y2))
1157 // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1158 // Selection spans a hidden region
1159 if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1167 fixedRight = y2 - 1;
1174 List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1175 int g, groupSize = vseqs.size();
1176 SequenceI[] groupSeqs = new SequenceI[groupSize];
1177 for (g = 0; g < groupSeqs.length; g++)
1179 groupSeqs[g] = vseqs.get(g);
1185 // If the user has selected the whole sequence, and is dragging to
1186 // the right, we can still extend the alignment and selectionGroup
1187 if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1188 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1190 sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1191 fixedRight = sg.getEndRes();
1194 // Is it valid with fixed columns??
1195 // Find the next gap before the end
1196 // of the visible region boundary
1197 boolean blank = false;
1198 for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1202 for (g = 0; g < groupSize; g++)
1204 for (int j = 0; j < startres - lastres; j++)
1206 if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1221 if (sg.getSize() == av.getAlignment().getHeight())
1223 if ((av.hasHiddenColumns() && startres < av
1224 .getColumnSelection().getHiddenBoundaryRight(startres)))
1230 int alWidth = av.getAlignment().getWidth();
1231 if (av.hasHiddenRows())
1233 int hwidth = av.getAlignment().getHiddenSequences()
1235 if (hwidth > alWidth)
1240 // We can still insert gaps if the selectionGroup
1241 // contains all the sequences
1242 sg.setEndRes(sg.getEndRes() + startres - lastres);
1243 fixedRight = alWidth + startres - lastres;
1254 else if (!insertGap)
1256 // / Are we able to delete?
1257 // ie are all columns blank?
1259 for (g = 0; g < groupSize; g++)
1261 for (int j = startres; j < lastres; j++)
1263 if (groupSeqs[g].getLength() <= j)
1268 if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1270 // Not a gap, block edit not valid
1280 // dragging to the right
1281 if (fixedColumns && fixedRight != -1)
1283 for (int j = lastres; j < startres; j++)
1285 insertChar(j, groupSeqs, fixedRight);
1290 appendEdit(Action.INSERT_GAP, groupSeqs, startres, startres
1296 // dragging to the left
1297 if (fixedColumns && fixedRight != -1)
1299 for (int j = lastres; j > startres; j--)
1301 deleteChar(startres, groupSeqs, fixedRight);
1306 appendEdit(Action.DELETE_GAP, groupSeqs, startres, lastres
1313 // ///Editing a single sequence///////////
1317 // dragging to the right
1318 if (fixedColumns && fixedRight != -1)
1320 for (int j = lastres; j < startres; j++)
1322 insertChar(j, new SequenceI[] { seq }, fixedRight);
1327 appendEdit(Action.INSERT_GAP, new SequenceI[] { seq }, lastres,
1328 startres - lastres);
1335 // dragging to the left
1336 if (fixedColumns && fixedRight != -1)
1338 for (int j = lastres; j > startres; j--)
1340 if (!Comparison.isGap(seq.getCharAt(startres)))
1345 deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1350 // could be a keyboard edit trying to delete none gaps
1352 for (int m = startres; m < lastres; m++)
1354 if (!Comparison.isGap(seq.getCharAt(m)))
1363 appendEdit(Action.DELETE_GAP, new SequenceI[] { seq },
1369 {// insertGap==false AND editSeq==TRUE;
1370 if (fixedColumns && fixedRight != -1)
1372 for (int j = lastres; j < startres; j++)
1374 insertChar(j, new SequenceI[] { seq }, fixedRight);
1379 appendEdit(Action.INSERT_NUC, new SequenceI[] { seq }, lastres,
1380 startres - lastres);
1387 seqCanvas.repaint();
1390 void insertChar(int j, SequenceI[] seq, int fixedColumn)
1392 int blankColumn = fixedColumn;
1393 for (int s = 0; s < seq.length; s++)
1395 // Find the next gap before the end of the visible region boundary
1396 // If lastCol > j, theres a boundary after the gap insertion
1398 for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1400 if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1402 // Theres a space, so break and insert the gap
1407 if (blankColumn <= j)
1409 blankColumn = fixedColumn;
1415 appendEdit(Action.DELETE_GAP, seq, blankColumn, 1);
1417 appendEdit(Action.INSERT_GAP, seq, j, 1);
1422 * Helper method to add and perform one edit action.
1429 protected void appendEdit(Action action, SequenceI[] seq, int pos,
1433 final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1434 av.getAlignment().getGapCharacter());
1436 editCommand.appendEdit(edit, av.getAlignment(), true, null);
1439 void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1442 appendEdit(Action.DELETE_GAP, seq, j, 1);
1444 appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1);
1454 public void mouseEntered(MouseEvent e)
1461 if (scrollThread != null)
1463 scrollThread.running = false;
1464 scrollThread = null;
1475 public void mouseExited(MouseEvent e)
1477 if (av.getWrapAlignment())
1484 scrollThread = new ScrollThread();
1489 * Handler for double-click on a position with one or more sequence features.
1490 * Opens the Amend Features dialog to allow feature details to be amended, or
1491 * the feature deleted.
1494 public void mouseClicked(MouseEvent evt)
1496 SequenceGroup sg = null;
1497 SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
1498 if (evt.getClickCount() > 1)
1500 sg = av.getSelectionGroup();
1501 if (sg != null && sg.getSize() == 1
1502 && sg.getEndRes() - sg.getStartRes() < 2)
1504 av.setSelectionGroup(null);
1507 List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1508 .findFeaturesAtRes(sequence.getDatasetSequence(),
1509 sequence.findPosition(findRes(evt)));
1511 if (!features.isEmpty())
1514 * highlight the first feature at the position on the alignment
1516 SearchResultsI highlight = new SearchResults();
1517 highlight.addResult(sequence, features.get(0).getBegin(), features
1519 seqCanvas.highlightSearchResults(highlight);
1522 * open the Amend Features dialog; clear highlighting afterwards,
1523 * whether changes were made or not
1525 List<SequenceI> seqs = Collections.singletonList(sequence);
1526 seqCanvas.getFeatureRenderer().amendFeatures(seqs, features, false,
1528 seqCanvas.highlightSearchResults(null);
1534 public void mouseWheelMoved(MouseWheelEvent e)
1537 if (e.getWheelRotation() > 0)
1539 if (e.isShiftDown())
1541 ap.scrollRight(true);
1551 if (e.isShiftDown())
1553 ap.scrollRight(false);
1560 // TODO Update tooltip for new position.
1569 public void doMousePressedDefineMode(MouseEvent evt)
1571 final int res = findRes(evt);
1572 final int seq = findSeq(evt);
1574 needOverviewUpdate = false;
1576 startWrapBlock = wrappedBlock;
1578 if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1580 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
1581 .getString("label.cannot_edit_annotations_in_wrapped_view"),
1582 MessageManager.getString("label.wrapped_view_no_edit"),
1583 JvOptionPane.WARNING_MESSAGE);
1587 if (seq < 0 || res < 0)
1592 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1594 if ((sequence == null) || (res > sequence.getLength()))
1599 stretchGroup = av.getSelectionGroup();
1601 if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1603 stretchGroup = av.getAlignment().findGroup(sequence, res);
1604 if (stretchGroup != null)
1606 // only update the current selection if the popup menu has a group to
1608 av.setSelectionGroup(stretchGroup);
1612 if (evt.isPopupTrigger()) // Mac: mousePressed
1619 * defer right-mouse click handling to mouseReleased on Windows
1620 * (where isPopupTrigger() will answer true)
1621 * NB isRightMouseButton is also true for Cmd-click on Mac
1623 if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1630 seqCanvas.cursorX = findRes(evt);
1631 seqCanvas.cursorY = findSeq(evt);
1632 seqCanvas.repaint();
1636 if (stretchGroup == null)
1638 // Only if left mouse button do we want to change group sizes
1640 // define a new group here
1641 SequenceGroup sg = new SequenceGroup();
1642 sg.setStartRes(res);
1644 sg.addSequence(sequence, false);
1645 av.setSelectionGroup(sg);
1648 if (av.getConservationSelected())
1650 SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1654 if (av.getAbovePIDThreshold())
1656 SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1659 // TODO: stretchGroup will always be not null. Is this a merge error ?
1660 if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1662 // Edit end res position of selected group
1663 changeEndRes = true;
1665 else if ((stretchGroup != null)
1666 && (stretchGroup.getStartRes() == res))
1668 // Edit end res position of selected group
1669 changeStartRes = true;
1671 stretchGroup.getWidth();
1674 seqCanvas.repaint();
1678 * Build and show a pop-up menu at the right-click mouse position
1684 void showPopupMenu(MouseEvent evt)
1686 final int res = findRes(evt);
1687 final int seq = findSeq(evt);
1688 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1689 List<SequenceFeature> allFeatures = ap.getFeatureRenderer()
1690 .findFeaturesAtRes(sequence.getDatasetSequence(),
1691 sequence.findPosition(res));
1692 List<String> links = new ArrayList<String>();
1693 for (SequenceFeature sf : allFeatures)
1695 if (sf.links != null)
1697 for (String link : sf.links)
1704 PopupMenu pop = new PopupMenu(ap, null, links);
1705 pop.show(this, evt.getX(), evt.getY());
1714 public void doMouseReleasedDefineMode(MouseEvent evt)
1716 if (stretchGroup == null)
1720 // always do this - annotation has own state
1721 // but defer colourscheme update until hidden sequences are passed in
1722 boolean vischange = stretchGroup.recalcConservation(true);
1723 needOverviewUpdate |= vischange && av.isSelectionDefinedGroup();
1724 if (stretchGroup.cs != null)
1726 stretchGroup.cs.alignmentChanged(stretchGroup,
1727 av.getHiddenRepSequences());
1729 ResidueShaderI groupColourScheme = stretchGroup.getGroupColourScheme();
1730 String name = stretchGroup.getName();
1731 if (stretchGroup.cs.conservationApplied())
1733 SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1735 if (stretchGroup.cs.getThreshold() > 0)
1737 SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1740 PaintRefresher.Refresh(this, av.getSequenceSetId());
1741 ap.paintAlignment(needOverviewUpdate);
1742 needOverviewUpdate = false;
1743 changeEndRes = false;
1744 changeStartRes = false;
1745 stretchGroup = null;
1755 public void doMouseDraggedDefineMode(MouseEvent evt)
1757 int res = findRes(evt);
1758 int y = findSeq(evt);
1760 if (wrappedBlock != startWrapBlock)
1765 if (stretchGroup == null)
1770 if (res >= av.getAlignment().getWidth())
1772 res = av.getAlignment().getWidth() - 1;
1775 if (stretchGroup.getEndRes() == res)
1777 // Edit end res position of selected group
1778 changeEndRes = true;
1780 else if (stretchGroup.getStartRes() == res)
1782 // Edit start res position of selected group
1783 changeStartRes = true;
1786 if (res < av.getRanges().getStartRes())
1788 res = av.getRanges().getStartRes();
1793 if (res > (stretchGroup.getStartRes() - 1))
1795 stretchGroup.setEndRes(res);
1796 needOverviewUpdate |= av.isSelectionDefinedGroup();
1799 else if (changeStartRes)
1801 if (res < (stretchGroup.getEndRes() + 1))
1803 stretchGroup.setStartRes(res);
1804 needOverviewUpdate |= av.isSelectionDefinedGroup();
1808 int dragDirection = 0;
1814 else if (y < oldSeq)
1819 while ((y != oldSeq) && (oldSeq > -1)
1820 && (y < av.getAlignment().getHeight()))
1822 // This routine ensures we don't skip any sequences, as the
1823 // selection is quite slow.
1824 Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1826 oldSeq += dragDirection;
1833 Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1835 if (stretchGroup.getSequences(null).contains(nextSeq))
1837 stretchGroup.deleteSequence(seq, false);
1838 needOverviewUpdate |= av.isSelectionDefinedGroup();
1844 stretchGroup.addSequence(seq, false);
1847 stretchGroup.addSequence(nextSeq, false);
1848 needOverviewUpdate |= av.isSelectionDefinedGroup();
1857 mouseDragging = true;
1859 if (scrollThread != null)
1861 scrollThread.setEvent(evt);
1864 seqCanvas.repaint();
1867 void scrollCanvas(MouseEvent evt)
1871 if (scrollThread != null)
1873 scrollThread.running = false;
1874 scrollThread = null;
1876 mouseDragging = false;
1880 if (scrollThread == null)
1882 scrollThread = new ScrollThread();
1885 mouseDragging = true;
1886 scrollThread.setEvent(evt);
1891 // this class allows scrolling off the bottom of the visible alignment
1892 class ScrollThread extends Thread
1896 boolean running = false;
1898 public ScrollThread()
1903 public void setEvent(MouseEvent e)
1908 public void stopScrolling()
1922 if (mouseDragging && (evt.getY() < 0)
1923 && (av.getRanges().getStartSeq() > 0))
1925 running = ap.scrollUp(true);
1928 if (mouseDragging && (evt.getY() >= getHeight())
1929 && (av.getAlignment().getHeight() > av.getRanges()
1932 running = ap.scrollUp(false);
1935 if (mouseDragging && (evt.getX() < 0))
1937 running = ap.scrollRight(false);
1939 else if (mouseDragging && (evt.getX() >= getWidth()))
1941 running = ap.scrollRight(true);
1948 } catch (Exception ex)
1956 * modify current selection according to a received message.
1959 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
1960 SelectionSource source)
1962 // TODO: fix this hack - source of messages is align viewport, but SeqPanel
1963 // handles selection messages...
1964 // TODO: extend config options to allow user to control if selections may be
1965 // shared between viewports.
1966 boolean iSentTheSelection = (av == source || (source instanceof AlignViewport && ((AlignmentViewport) source)
1967 .getSequenceSetId().equals(av.getSequenceSetId())));
1969 if (iSentTheSelection)
1971 // respond to our own event by updating dependent dialogs
1972 if (ap.getCalculationDialog() != null)
1974 ap.getCalculationDialog().validateCalcTypes();
1977 // process further ?
1978 if (!av.followSelection)
1985 * Ignore the selection if there is one of our own pending.
1987 if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
1993 * Check for selection in a view of which this one is a dna/protein
1996 if (selectionFromTranslation(seqsel, colsel, source))
2001 // do we want to thread this ? (contention with seqsel and colsel locks, I
2004 * only copy colsel if there is a real intersection between
2005 * sequence selection and this panel's alignment
2007 boolean repaint = false;
2008 boolean copycolsel = false;
2010 SequenceGroup sgroup = null;
2011 if (seqsel != null && seqsel.getSize() > 0)
2013 if (av.getAlignment() == null)
2015 Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2016 + " ViewId=" + av.getViewId()
2017 + " 's alignment is NULL! returning immediately.");
2020 sgroup = seqsel.intersect(av.getAlignment(),
2021 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2022 if ((sgroup != null && sgroup.getSize() > 0))
2027 if (sgroup != null && sgroup.getSize() > 0)
2029 av.setSelectionGroup(sgroup);
2033 av.setSelectionGroup(null);
2035 av.isSelectionGroupChanged(true);
2040 // the current selection is unset or from a previous message
2041 // so import the new colsel.
2042 if (colsel == null || colsel.isEmpty())
2044 if (av.getColumnSelection() != null)
2046 av.getColumnSelection().clear();
2052 // TODO: shift colSel according to the intersecting sequences
2053 if (av.getColumnSelection() == null)
2055 av.setColumnSelection(new ColumnSelection(colsel));
2059 av.getColumnSelection().setElementsFrom(colsel);
2062 av.isColSelChanged(true);
2067 && av.hasHiddenColumns()
2068 && (av.getColumnSelection() == null || av.getColumnSelection()
2069 .getHiddenColumns() == null))
2071 System.err.println("Bad things");
2073 if (repaint) // always true!
2075 // probably finessing with multiple redraws here
2076 PaintRefresher.Refresh(this, av.getSequenceSetId());
2077 // ap.paintAlignment(false);
2080 // lastly, update dependent dialogs
2081 if (ap.getCalculationDialog() != null)
2083 ap.getCalculationDialog().validateCalcTypes();
2089 * If this panel is a cdna/protein translation view of the selection source,
2090 * tries to map the source selection to a local one, and returns true. Else
2097 protected boolean selectionFromTranslation(SequenceGroup seqsel,
2098 ColumnSelection colsel, SelectionSource source)
2100 if (!(source instanceof AlignViewportI))
2104 final AlignViewportI sourceAv = (AlignViewportI) source;
2105 if (sourceAv.getCodingComplement() != av
2106 && av.getCodingComplement() != sourceAv)
2112 * Map sequence selection
2114 SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2115 av.setSelectionGroup(sg);
2116 av.isSelectionGroupChanged(true);
2119 * Map column selection
2121 ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2123 av.setColumnSelection(cs);
2125 // lastly, update any dependent dialogs
2126 if (ap.getCalculationDialog() != null)
2128 ap.getCalculationDialog().validateCalcTypes();
2131 PaintRefresher.Refresh(this, av.getSequenceSetId());