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 if (av.getWrapAlignment())
207 int hgap = av.getCharHeight();
208 if (av.getScaleAboveWrapped())
210 hgap += av.getCharHeight();
213 int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
214 + hgap + seqCanvas.getAnnotationHeight();
218 x -= seqCanvas.LABEL_WEST;
220 int cwidth = seqCanvas.getWrappedCanvasWidth(this.getWidth());
226 wrappedBlock = y / cHeight;
227 wrappedBlock += av.getRanges().getStartRes() / cwidth;
229 res = wrappedBlock * cwidth + x / av.getCharWidth();
234 if (x > seqCanvas.getX() + seqCanvas.getWidth())
236 // make sure we calculate relative to visible alignment, rather than
238 x = seqCanvas.getX() + seqCanvas.getWidth();
240 res = (x / av.getCharWidth()) + av.getRanges().getStartRes();
241 if (res > av.getRanges().getEndRes())
244 res = av.getRanges().getEndRes();
248 if (av.hasHiddenColumns())
250 res = av.getAlignment().getHiddenColumns()
251 .adjustForHiddenColumns(res);
258 int findSeq(MouseEvent evt)
263 if (av.getWrapAlignment())
265 int hgap = av.getCharHeight();
266 if (av.getScaleAboveWrapped())
268 hgap += av.getCharHeight();
271 int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
272 + hgap + seqCanvas.getAnnotationHeight();
276 seq = Math.min((y % cHeight) / av.getCharHeight(), av.getAlignment()
281 seq = Math.min((y / av.getCharHeight())
282 + av.getRanges().getStartSeq(),
284 .getAlignment().getHeight() - 1);
291 * When all of a sequence of edits are complete, put the resulting edit list
292 * on the history stack (undo list), and reset flags for editing in progress.
298 if (editCommand != null && editCommand.getSize() > 0)
300 ap.alignFrame.addHistoryItem(editCommand);
301 av.firePropertyChange("alignment", null, av.getAlignment()
307 * Tidy up come what may...
312 groupEditing = false;
321 seqCanvas.cursorY = getKeyboardNo1() - 1;
325 void setCursorColumn()
327 seqCanvas.cursorX = getKeyboardNo1() - 1;
331 void setCursorRowAndColumn()
333 if (keyboardNo2 == null)
335 keyboardNo2 = new StringBuffer();
339 seqCanvas.cursorX = getKeyboardNo1() - 1;
340 seqCanvas.cursorY = getKeyboardNo2() - 1;
345 void setCursorPosition()
347 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
349 seqCanvas.cursorX = sequence.findIndex(getKeyboardNo1()) - 1;
353 void moveCursor(int dx, int dy)
355 seqCanvas.cursorX += dx;
356 seqCanvas.cursorY += dy;
358 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
360 if (av.hasHiddenColumns()
361 && !hidden.isVisible(seqCanvas.cursorX))
363 int original = seqCanvas.cursorX - dx;
364 int maxWidth = av.getAlignment().getWidth();
366 while (!hidden.isVisible(seqCanvas.cursorX)
367 && seqCanvas.cursorX < maxWidth && seqCanvas.cursorX > 0)
369 seqCanvas.cursorX += dx;
372 if (seqCanvas.cursorX >= maxWidth
373 || !hidden.isVisible(seqCanvas.cursorX))
375 seqCanvas.cursorX = original;
382 void scrollToVisible()
384 if (seqCanvas.cursorX < 0)
386 seqCanvas.cursorX = 0;
388 else if (seqCanvas.cursorX > av.getAlignment().getWidth() - 1)
390 seqCanvas.cursorX = av.getAlignment().getWidth() - 1;
393 if (seqCanvas.cursorY < 0)
395 seqCanvas.cursorY = 0;
397 else if (seqCanvas.cursorY > av.getAlignment().getHeight() - 1)
399 seqCanvas.cursorY = av.getAlignment().getHeight() - 1;
403 if (av.getWrapAlignment())
405 ap.scrollToWrappedVisible(seqCanvas.cursorX);
409 while (seqCanvas.cursorY < av.getRanges().getStartSeq())
413 while (seqCanvas.cursorY > av.getRanges().getEndSeq())
417 if (!av.getWrapAlignment())
419 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
420 while (seqCanvas.cursorX < hidden.adjustForHiddenColumns(av
421 .getRanges().getStartRes()))
423 if (!ap.scrollRight(false))
428 while (seqCanvas.cursorX > hidden.adjustForHiddenColumns(av
429 .getRanges().getEndRes()))
431 if (!ap.scrollRight(true))
438 setStatusMessage(av.getAlignment().getSequenceAt(seqCanvas.cursorY),
439 seqCanvas.cursorX, seqCanvas.cursorY);
444 void setSelectionAreaAtCursor(boolean topLeft)
446 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
448 if (av.getSelectionGroup() != null)
450 SequenceGroup sg = av.getSelectionGroup();
451 // Find the top and bottom of this group
452 int min = av.getAlignment().getHeight(), max = 0;
453 for (int i = 0; i < sg.getSize(); i++)
455 int index = av.getAlignment().findIndex(sg.getSequenceAt(i));
470 sg.setStartRes(seqCanvas.cursorX);
471 if (sg.getEndRes() < seqCanvas.cursorX)
473 sg.setEndRes(seqCanvas.cursorX);
476 min = seqCanvas.cursorY;
480 sg.setEndRes(seqCanvas.cursorX);
481 if (sg.getStartRes() > seqCanvas.cursorX)
483 sg.setStartRes(seqCanvas.cursorX);
486 max = seqCanvas.cursorY + 1;
491 // Only the user can do this
492 av.setSelectionGroup(null);
496 // Now add any sequences between min and max
497 sg.getSequences(null).clear();
498 for (int i = min; i < max; i++)
500 sg.addSequence(av.getAlignment().getSequenceAt(i), false);
505 if (av.getSelectionGroup() == null)
507 SequenceGroup sg = new SequenceGroup();
508 sg.setStartRes(seqCanvas.cursorX);
509 sg.setEndRes(seqCanvas.cursorX);
510 sg.addSequence(sequence, false);
511 av.setSelectionGroup(sg);
514 ap.paintAlignment(false);
518 void insertGapAtCursor(boolean group)
520 groupEditing = group;
521 startseq = seqCanvas.cursorY;
522 lastres = seqCanvas.cursorX;
523 editSequence(true, false, seqCanvas.cursorX + getKeyboardNo1());
527 void deleteGapAtCursor(boolean group)
529 groupEditing = group;
530 startseq = seqCanvas.cursorY;
531 lastres = seqCanvas.cursorX + getKeyboardNo1();
532 editSequence(false, false, seqCanvas.cursorX);
536 void insertNucAtCursor(boolean group, String nuc)
538 // TODO not called - delete?
539 groupEditing = group;
540 startseq = seqCanvas.cursorY;
541 lastres = seqCanvas.cursorX;
542 editSequence(false, true, seqCanvas.cursorX + getKeyboardNo1());
546 void numberPressed(char value)
548 if (keyboardNo1 == null)
550 keyboardNo1 = new StringBuffer();
553 if (keyboardNo2 != null)
555 keyboardNo2.append(value);
559 keyboardNo1.append(value);
567 if (keyboardNo1 != null)
569 int value = Integer.parseInt(keyboardNo1.toString());
573 } catch (Exception x)
584 if (keyboardNo2 != null)
586 int value = Integer.parseInt(keyboardNo2.toString());
590 } catch (Exception x)
604 public void mouseReleased(MouseEvent evt)
606 mouseDragging = false;
607 mouseWheelPressed = false;
609 if (evt.isPopupTrigger()) // Windows: mouseReleased
618 doMouseReleasedDefineMode(evt);
632 public void mousePressed(MouseEvent evt)
634 lastMousePress = evt.getPoint();
636 if (SwingUtilities.isMiddleMouseButton(evt))
638 mouseWheelPressed = true;
642 boolean isControlDown = Platform.isControlDown(evt);
643 if (evt.isShiftDown() || isControlDown)
653 doMousePressedDefineMode(evt);
657 int seq = findSeq(evt);
658 int res = findColumn(evt);
660 if (seq < 0 || res < 0)
665 if ((seq < av.getAlignment().getHeight())
666 && (res < av.getAlignment().getSequenceAt(seq).getLength()))
683 public void mouseOverSequence(SequenceI sequence, int index, int pos)
685 String tmp = sequence.hashCode() + " " + index + " " + pos;
687 if (lastMessage == null || !lastMessage.equals(tmp))
689 // System.err.println("mouseOver Sequence: "+tmp);
690 ssm.mouseOverSequence(sequence, index, pos, av);
696 * Highlight the mapped region described by the search results object (unless
697 * unchanged). This supports highlight of protein while mousing over linked
698 * cDNA and vice versa. The status bar is also updated to show the location of
699 * the start of the highlighted region.
702 public void highlightSequence(SearchResultsI results)
704 if (results == null || results.equals(lastSearchResults))
708 lastSearchResults = results;
710 if (av.isFollowHighlight())
713 * if scrollToPosition requires a scroll adjustment, this flag prevents
714 * another scroll event being propagated back to the originator
716 * @see AlignmentPanel#adjustmentValueChanged
718 ap.setDontScrollComplement(true);
719 if (ap.scrollToPosition(results, false))
721 seqCanvas.revalidate();
724 setStatusMessage(results);
725 seqCanvas.highlightSearchResults(results);
729 public VamsasSource getVamsasSource()
731 return this.ap == null ? null : this.ap.av;
735 public void updateColours(SequenceI seq, int index)
737 System.out.println("update the seqPanel colours");
748 public void mouseMoved(MouseEvent evt)
752 // This is because MacOSX creates a mouseMoved
753 // If control is down, other platforms will not.
757 final int column = findColumn(evt);
758 int seq = findSeq(evt);
759 if (column < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
763 if (column == lastMouseColumn && seq == lastMouseSeq)
766 * just a pixel move without change of residue
770 lastMouseColumn = column;
773 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
775 if (column >= sequence.getLength())
781 * set status bar message, returning residue position in sequence
783 final int pos = setStatusMessage(sequence, column, seq);
784 if (ssm != null && pos > -1)
786 mouseOverSequence(sequence, column, pos);
789 tooltipText.setLength(6); // Cuts the buffer back to <html>
791 SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
794 for (int g = 0; g < groups.length; g++)
796 if (groups[g].getStartRes() <= column
797 && groups[g].getEndRes() >= column)
799 if (!groups[g].getName().startsWith("JTreeGroup")
800 && !groups[g].getName().startsWith("JGroup"))
802 tooltipText.append(groups[g].getName());
805 if (groups[g].getDescription() != null)
807 tooltipText.append(": " + groups[g].getDescription());
813 if (av.isShowSequenceFeatures())
815 List<SequenceFeature> features = ap.getFeatureRenderer()
816 .findFeaturesAtRes(sequence.getDatasetSequence(), pos);
817 seqARep.appendFeatures(tooltipText, pos, features,
818 this.ap.getSeqPanel().seqCanvas.fr.getMinMax());
820 if (tooltipText.length() == 6) // <html>
822 setToolTipText(null);
827 String textString = tooltipText.toString();
828 if (lastTooltip == null || !lastTooltip.equals(textString))
830 String formatedTooltipText = JvSwingUtils.wrapTooltip(true,
832 setToolTipText(formatedTooltipText);
833 lastTooltip = textString;
838 private Point lastp = null;
843 * @see javax.swing.JComponent#getToolTipLocation(java.awt.event.MouseEvent)
846 public Point getToolTipLocation(MouseEvent event)
848 int x = event.getX(), w = getWidth();
849 int wdth = (w - x < 200) ? -(w / 2) : 5; // switch sides when tooltip is too
852 if (!event.isShiftDown() || p == null)
854 p = (tooltipText != null && tooltipText.length() > 6) ? new Point(
855 event.getX() + wdth, event.getY() - 20) : null;
858 * TODO: try to modify position region is not obcured by tooltip
866 * set when the current UI interaction has resulted in a change that requires
867 * overview shading to be recalculated. this could be changed to something
868 * more expressive that indicates what actually has changed, so selective
869 * redraws can be applied
871 private boolean needOverviewUpdate = false; // TODO: refactor to avcontroller
874 * set if av.getSelectionGroup() refers to a group that is defined on the
875 * alignment view, rather than a transient selection
877 // private boolean editingDefinedGroup = false; // TODO: refactor to
878 // avcontroller or viewModel
881 * Sets the status message in alignment panel, showing the sequence number
882 * (index) and id, residue and residue position for the given sequence and
883 * column position. Returns the calculated residue position in the sequence.
886 * aligned sequence object
890 * index of sequence in alignment
891 * @return position of res in sequence
893 int setStatusMessage(SequenceI sequence, final int column, int seq)
895 StringBuilder text = new StringBuilder(32);
898 * Sequence number (if known), and sequence name.
900 String seqno = seq == -1 ? "" : " " + (seq + 1);
901 text.append("Sequence").append(seqno).append(" ID: ")
902 .append(sequence.getName());
904 String residue = null;
906 * Try to translate the display character to residue name (null for gap).
908 final String displayChar = String.valueOf(sequence.getCharAt(column));
909 if (av.getAlignment().isNucleotide())
911 residue = ResidueProperties.nucleotideName.get(displayChar);
914 text.append(" Nucleotide: ").append(residue);
919 residue = "X".equalsIgnoreCase(displayChar) ? "X" : ("*"
920 .equals(displayChar) ? "STOP" : ResidueProperties.aa2Triplet
924 text.append(" Residue: ").append(residue);
931 pos = sequence.findPosition(column);
932 text.append(" (").append(Integer.toString(pos)).append(")");
934 ap.alignFrame.statusBar.setText(text.toString());
939 * Set the status bar message to highlight the first matched position in
944 private void setStatusMessage(SearchResultsI results)
946 AlignmentI al = this.av.getAlignment();
947 int sequenceIndex = al.findIndex(results);
948 if (sequenceIndex == -1)
952 SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
953 for (SearchResultMatchI m : results.getResults())
955 SequenceI seq = m.getSequence();
956 if (seq.getDatasetSequence() != null)
958 seq = seq.getDatasetSequence();
964 * Convert position in sequence (base 1) to sequence character array
967 int start = m.getStart() - m.getSequence().getStart();
968 setStatusMessage(seq, start, sequenceIndex);
978 public void mouseDragged(MouseEvent evt)
980 if (mouseWheelPressed)
982 boolean inSplitFrame = ap.av.getCodingComplement() != null;
983 boolean copyChanges = inSplitFrame && av.isProteinFontAsCdna();
985 int oldWidth = av.getCharWidth();
987 // Which is bigger, left-right or up-down?
988 if (Math.abs(evt.getY() - lastMousePress.getY()) > Math.abs(evt
989 .getX() - lastMousePress.getX()))
992 * on drag up or down, decrement or increment font size
994 int fontSize = av.font.getSize();
995 boolean fontChanged = false;
997 if (evt.getY() < lastMousePress.getY())
1002 else if (evt.getY() > lastMousePress.getY())
1015 Font newFont = new Font(av.font.getName(), av.font.getStyle(),
1017 av.setFont(newFont, true);
1018 av.setCharWidth(oldWidth);
1022 ap.av.getCodingComplement().setFont(newFont, true);
1023 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1024 .getSplitViewContainer();
1025 splitFrame.adjustLayout();
1026 splitFrame.repaint();
1033 * on drag left or right, decrement or increment character width
1036 if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
1038 newWidth = av.getCharWidth() - 1;
1039 av.setCharWidth(newWidth);
1041 else if (evt.getX() > lastMousePress.getX())
1043 newWidth = av.getCharWidth() + 1;
1044 av.setCharWidth(newWidth);
1048 ap.paintAlignment(false);
1052 * need to ensure newWidth is set on cdna, regardless of which
1053 * panel the mouse drag happened in; protein will compute its
1054 * character width as 1:1 or 3:1
1056 av.getCodingComplement().setCharWidth(newWidth);
1057 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1058 .getSplitViewContainer();
1059 splitFrame.adjustLayout();
1060 splitFrame.repaint();
1065 FontMetrics fm = getFontMetrics(av.getFont());
1066 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1068 lastMousePress = evt.getPoint();
1075 doMouseDraggedDefineMode(evt);
1079 int res = findColumn(evt);
1086 if ((lastres == -1) || (lastres == res))
1091 if ((res < av.getAlignment().getWidth()) && (res < lastres))
1093 // dragLeft, delete gap
1094 editSequence(false, false, res);
1098 editSequence(true, false, res);
1101 mouseDragging = true;
1102 if (scrollThread != null)
1104 scrollThread.setEvent(evt);
1108 // TODO: Make it more clever than many booleans
1109 synchronized void editSequence(boolean insertGap, boolean editSeq,
1113 int fixedRight = -1;
1114 boolean fixedColumns = false;
1115 SequenceGroup sg = av.getSelectionGroup();
1117 SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1119 // No group, but the sequence may represent a group
1120 if (!groupEditing && av.hasHiddenRows())
1122 if (av.isHiddenRepSequence(seq))
1124 sg = av.getRepresentedSequences(seq);
1125 groupEditing = true;
1129 StringBuilder message = new StringBuilder(64);
1132 message.append("Edit group:");
1133 if (editCommand == null)
1135 editCommand = new EditCommand(
1136 MessageManager.getString("action.edit_group"));
1141 message.append("Edit sequence: " + seq.getName());
1142 String label = seq.getName();
1143 if (label.length() > 10)
1145 label = label.substring(0, 10);
1147 if (editCommand == null)
1149 editCommand = new EditCommand(MessageManager.formatMessage(
1150 "label.edit_params", new String[] { label }));
1156 message.append(" insert ");
1160 message.append(" delete ");
1163 message.append(Math.abs(startres - lastres) + " gaps.");
1164 ap.alignFrame.statusBar.setText(message.toString());
1166 // Are we editing within a selection group?
1168 || (sg != null && sg.getSequences(av.getHiddenRepSequences())
1171 fixedColumns = true;
1173 // sg might be null as the user may only see 1 sequence,
1174 // but the sequence represents a group
1177 if (!av.isHiddenRepSequence(seq))
1182 sg = av.getRepresentedSequences(seq);
1185 fixedLeft = sg.getStartRes();
1186 fixedRight = sg.getEndRes();
1188 if ((startres < fixedLeft && lastres >= fixedLeft)
1189 || (startres >= fixedLeft && lastres < fixedLeft)
1190 || (startres > fixedRight && lastres <= fixedRight)
1191 || (startres <= fixedRight && lastres > fixedRight))
1197 if (fixedLeft > startres)
1199 fixedRight = fixedLeft - 1;
1202 else if (fixedRight < startres)
1204 fixedLeft = fixedRight;
1209 if (av.hasHiddenColumns())
1211 fixedColumns = true;
1212 int y1 = av.getAlignment().getHiddenColumns()
1213 .getHiddenBoundaryLeft(startres);
1214 int y2 = av.getAlignment().getHiddenColumns()
1215 .getHiddenBoundaryRight(startres);
1217 if ((insertGap && startres > y1 && lastres < y1)
1218 || (!insertGap && startres < y2 && lastres > y2))
1224 // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1225 // Selection spans a hidden region
1226 if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1234 fixedRight = y2 - 1;
1241 List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1242 int g, groupSize = vseqs.size();
1243 SequenceI[] groupSeqs = new SequenceI[groupSize];
1244 for (g = 0; g < groupSeqs.length; g++)
1246 groupSeqs[g] = vseqs.get(g);
1252 // If the user has selected the whole sequence, and is dragging to
1253 // the right, we can still extend the alignment and selectionGroup
1254 if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1255 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1257 sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1258 fixedRight = sg.getEndRes();
1261 // Is it valid with fixed columns??
1262 // Find the next gap before the end
1263 // of the visible region boundary
1264 boolean blank = false;
1265 for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1269 for (g = 0; g < groupSize; g++)
1271 for (int j = 0; j < startres - lastres; j++)
1273 if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1288 if (sg.getSize() == av.getAlignment().getHeight())
1290 if ((av.hasHiddenColumns() && startres < av.getAlignment()
1291 .getHiddenColumns().getHiddenBoundaryRight(startres)))
1297 int alWidth = av.getAlignment().getWidth();
1298 if (av.hasHiddenRows())
1300 int hwidth = av.getAlignment().getHiddenSequences()
1302 if (hwidth > alWidth)
1307 // We can still insert gaps if the selectionGroup
1308 // contains all the sequences
1309 sg.setEndRes(sg.getEndRes() + startres - lastres);
1310 fixedRight = alWidth + startres - lastres;
1321 else if (!insertGap)
1323 // / Are we able to delete?
1324 // ie are all columns blank?
1326 for (g = 0; g < groupSize; g++)
1328 for (int j = startres; j < lastres; j++)
1330 if (groupSeqs[g].getLength() <= j)
1335 if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1337 // Not a gap, block edit not valid
1347 // dragging to the right
1348 if (fixedColumns && fixedRight != -1)
1350 for (int j = lastres; j < startres; j++)
1352 insertChar(j, groupSeqs, fixedRight);
1357 appendEdit(Action.INSERT_GAP, groupSeqs, startres, startres
1363 // dragging to the left
1364 if (fixedColumns && fixedRight != -1)
1366 for (int j = lastres; j > startres; j--)
1368 deleteChar(startres, groupSeqs, fixedRight);
1373 appendEdit(Action.DELETE_GAP, groupSeqs, startres, lastres
1380 // ///Editing a single sequence///////////
1384 // dragging to the right
1385 if (fixedColumns && fixedRight != -1)
1387 for (int j = lastres; j < startres; j++)
1389 insertChar(j, new SequenceI[] { seq }, fixedRight);
1394 appendEdit(Action.INSERT_GAP, new SequenceI[] { seq }, lastres,
1395 startres - lastres);
1402 // dragging to the left
1403 if (fixedColumns && fixedRight != -1)
1405 for (int j = lastres; j > startres; j--)
1407 if (!Comparison.isGap(seq.getCharAt(startres)))
1412 deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1417 // could be a keyboard edit trying to delete none gaps
1419 for (int m = startres; m < lastres; m++)
1421 if (!Comparison.isGap(seq.getCharAt(m)))
1430 appendEdit(Action.DELETE_GAP, new SequenceI[] { seq },
1436 {// insertGap==false AND editSeq==TRUE;
1437 if (fixedColumns && fixedRight != -1)
1439 for (int j = lastres; j < startres; j++)
1441 insertChar(j, new SequenceI[] { seq }, fixedRight);
1446 appendEdit(Action.INSERT_NUC, new SequenceI[] { seq }, lastres,
1447 startres - lastres);
1454 seqCanvas.repaint();
1457 void insertChar(int j, SequenceI[] seq, int fixedColumn)
1459 int blankColumn = fixedColumn;
1460 for (int s = 0; s < seq.length; s++)
1462 // Find the next gap before the end of the visible region boundary
1463 // If lastCol > j, theres a boundary after the gap insertion
1465 for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1467 if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1469 // Theres a space, so break and insert the gap
1474 if (blankColumn <= j)
1476 blankColumn = fixedColumn;
1482 appendEdit(Action.DELETE_GAP, seq, blankColumn, 1);
1484 appendEdit(Action.INSERT_GAP, seq, j, 1);
1489 * Helper method to add and perform one edit action.
1496 protected void appendEdit(Action action, SequenceI[] seq, int pos,
1500 final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1501 av.getAlignment().getGapCharacter());
1503 editCommand.appendEdit(edit, av.getAlignment(), true, null);
1506 void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1509 appendEdit(Action.DELETE_GAP, seq, j, 1);
1511 appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1);
1521 public void mouseEntered(MouseEvent e)
1528 if (scrollThread != null)
1530 scrollThread.running = false;
1531 scrollThread = null;
1542 public void mouseExited(MouseEvent e)
1544 if (av.getWrapAlignment())
1551 scrollThread = new ScrollThread();
1556 * Handler for double-click on a position with one or more sequence features.
1557 * Opens the Amend Features dialog to allow feature details to be amended, or
1558 * the feature deleted.
1561 public void mouseClicked(MouseEvent evt)
1563 SequenceGroup sg = null;
1564 SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
1565 if (evt.getClickCount() > 1)
1567 sg = av.getSelectionGroup();
1568 if (sg != null && sg.getSize() == 1
1569 && sg.getEndRes() - sg.getStartRes() < 2)
1571 av.setSelectionGroup(null);
1574 List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1575 .findFeaturesAtRes(sequence.getDatasetSequence(),
1576 sequence.findPosition(findColumn(evt)));
1578 if (!features.isEmpty())
1581 * highlight the first feature at the position on the alignment
1583 SearchResultsI highlight = new SearchResults();
1584 highlight.addResult(sequence, features.get(0).getBegin(), features
1586 seqCanvas.highlightSearchResults(highlight);
1589 * open the Amend Features dialog; clear highlighting afterwards,
1590 * whether changes were made or not
1592 List<SequenceI> seqs = Collections.singletonList(sequence);
1593 seqCanvas.getFeatureRenderer().amendFeatures(seqs, features, false,
1595 seqCanvas.highlightSearchResults(null);
1601 public void mouseWheelMoved(MouseWheelEvent e)
1604 if (e.getWheelRotation() > 0)
1606 if (e.isShiftDown())
1608 ap.scrollRight(true);
1618 if (e.isShiftDown())
1620 ap.scrollRight(false);
1627 // TODO Update tooltip for new position.
1636 public void doMousePressedDefineMode(MouseEvent evt)
1638 final int res = findColumn(evt);
1639 final int seq = findSeq(evt);
1641 needOverviewUpdate = false;
1643 startWrapBlock = wrappedBlock;
1645 if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1647 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
1648 .getString("label.cannot_edit_annotations_in_wrapped_view"),
1649 MessageManager.getString("label.wrapped_view_no_edit"),
1650 JvOptionPane.WARNING_MESSAGE);
1654 if (seq < 0 || res < 0)
1659 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1661 if ((sequence == null) || (res > sequence.getLength()))
1666 stretchGroup = av.getSelectionGroup();
1668 if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1670 stretchGroup = av.getAlignment().findGroup(sequence, res);
1671 if (stretchGroup != null)
1673 // only update the current selection if the popup menu has a group to
1675 av.setSelectionGroup(stretchGroup);
1679 if (evt.isPopupTrigger()) // Mac: mousePressed
1686 * defer right-mouse click handling to mouseReleased on Windows
1687 * (where isPopupTrigger() will answer true)
1688 * NB isRightMouseButton is also true for Cmd-click on Mac
1690 if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1697 seqCanvas.cursorX = findColumn(evt);
1698 seqCanvas.cursorY = findSeq(evt);
1699 seqCanvas.repaint();
1703 if (stretchGroup == null)
1705 // Only if left mouse button do we want to change group sizes
1707 // define a new group here
1708 SequenceGroup sg = new SequenceGroup();
1709 sg.setStartRes(res);
1711 sg.addSequence(sequence, false);
1712 av.setSelectionGroup(sg);
1715 if (av.getConservationSelected())
1717 SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1721 if (av.getAbovePIDThreshold())
1723 SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1726 // TODO: stretchGroup will always be not null. Is this a merge error ?
1727 if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1729 // Edit end res position of selected group
1730 changeEndRes = true;
1732 else if ((stretchGroup != null)
1733 && (stretchGroup.getStartRes() == res))
1735 // Edit end res position of selected group
1736 changeStartRes = true;
1738 stretchGroup.getWidth();
1741 seqCanvas.repaint();
1745 * Build and show a pop-up menu at the right-click mouse position
1751 void showPopupMenu(MouseEvent evt)
1753 final int res = findColumn(evt);
1754 final int seq = findSeq(evt);
1755 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1756 List<SequenceFeature> allFeatures = ap.getFeatureRenderer()
1757 .findFeaturesAtRes(sequence.getDatasetSequence(),
1758 sequence.findPosition(res));
1759 List<String> links = new ArrayList<String>();
1760 for (SequenceFeature sf : allFeatures)
1762 if (sf.links != null)
1764 for (String link : sf.links)
1771 PopupMenu pop = new PopupMenu(ap, null, links);
1772 pop.show(this, evt.getX(), evt.getY());
1781 public void doMouseReleasedDefineMode(MouseEvent evt)
1783 if (stretchGroup == null)
1787 // always do this - annotation has own state
1788 // but defer colourscheme update until hidden sequences are passed in
1789 boolean vischange = stretchGroup.recalcConservation(true);
1790 needOverviewUpdate |= vischange && av.isSelectionDefinedGroup();
1791 if (stretchGroup.cs != null)
1793 stretchGroup.cs.alignmentChanged(stretchGroup,
1794 av.getHiddenRepSequences());
1796 ResidueShaderI groupColourScheme = stretchGroup.getGroupColourScheme();
1797 String name = stretchGroup.getName();
1798 if (stretchGroup.cs.conservationApplied())
1800 SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1802 if (stretchGroup.cs.getThreshold() > 0)
1804 SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1807 PaintRefresher.Refresh(this, av.getSequenceSetId());
1808 ap.paintAlignment(needOverviewUpdate);
1809 needOverviewUpdate = false;
1810 changeEndRes = false;
1811 changeStartRes = false;
1812 stretchGroup = null;
1822 public void doMouseDraggedDefineMode(MouseEvent evt)
1824 int res = findColumn(evt);
1825 int y = findSeq(evt);
1827 if (wrappedBlock != startWrapBlock)
1832 if (stretchGroup == null)
1837 if (res >= av.getAlignment().getWidth())
1839 res = av.getAlignment().getWidth() - 1;
1842 if (stretchGroup.getEndRes() == res)
1844 // Edit end res position of selected group
1845 changeEndRes = true;
1847 else if (stretchGroup.getStartRes() == res)
1849 // Edit start res position of selected group
1850 changeStartRes = true;
1853 if (res < av.getRanges().getStartRes())
1855 res = av.getRanges().getStartRes();
1860 if (res > (stretchGroup.getStartRes() - 1))
1862 stretchGroup.setEndRes(res);
1863 needOverviewUpdate |= av.isSelectionDefinedGroup();
1866 else if (changeStartRes)
1868 if (res < (stretchGroup.getEndRes() + 1))
1870 stretchGroup.setStartRes(res);
1871 needOverviewUpdate |= av.isSelectionDefinedGroup();
1875 int dragDirection = 0;
1881 else if (y < oldSeq)
1886 while ((y != oldSeq) && (oldSeq > -1)
1887 && (y < av.getAlignment().getHeight()))
1889 // This routine ensures we don't skip any sequences, as the
1890 // selection is quite slow.
1891 Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1893 oldSeq += dragDirection;
1900 Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1902 if (stretchGroup.getSequences(null).contains(nextSeq))
1904 stretchGroup.deleteSequence(seq, false);
1905 needOverviewUpdate |= av.isSelectionDefinedGroup();
1911 stretchGroup.addSequence(seq, false);
1914 stretchGroup.addSequence(nextSeq, false);
1915 needOverviewUpdate |= av.isSelectionDefinedGroup();
1924 mouseDragging = true;
1926 if (scrollThread != null)
1928 scrollThread.setEvent(evt);
1931 seqCanvas.repaint();
1934 void scrollCanvas(MouseEvent evt)
1938 if (scrollThread != null)
1940 scrollThread.running = false;
1941 scrollThread = null;
1943 mouseDragging = false;
1947 if (scrollThread == null)
1949 scrollThread = new ScrollThread();
1952 mouseDragging = true;
1953 scrollThread.setEvent(evt);
1958 // this class allows scrolling off the bottom of the visible alignment
1959 class ScrollThread extends Thread
1963 boolean running = false;
1965 public ScrollThread()
1970 public void setEvent(MouseEvent e)
1975 public void stopScrolling()
1989 if (mouseDragging && (evt.getY() < 0)
1990 && (av.getRanges().getStartSeq() > 0))
1992 running = ap.scrollUp(true);
1995 if (mouseDragging && (evt.getY() >= getHeight())
1996 && (av.getAlignment().getHeight() > av.getRanges()
1999 running = ap.scrollUp(false);
2002 if (mouseDragging && (evt.getX() < 0))
2004 running = ap.scrollRight(false);
2006 else if (mouseDragging && (evt.getX() >= getWidth()))
2008 running = ap.scrollRight(true);
2015 } catch (Exception ex)
2023 * modify current selection according to a received message.
2026 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
2027 HiddenColumns hidden, SelectionSource source)
2029 // TODO: fix this hack - source of messages is align viewport, but SeqPanel
2030 // handles selection messages...
2031 // TODO: extend config options to allow user to control if selections may be
2032 // shared between viewports.
2033 boolean iSentTheSelection = (av == source || (source instanceof AlignViewport && ((AlignmentViewport) source)
2034 .getSequenceSetId().equals(av.getSequenceSetId())));
2036 if (iSentTheSelection)
2038 // respond to our own event by updating dependent dialogs
2039 if (ap.getCalculationDialog() != null)
2041 ap.getCalculationDialog().validateCalcTypes();
2044 // process further ?
2045 if (!av.followSelection)
2052 * Ignore the selection if there is one of our own pending.
2054 if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
2060 * Check for selection in a view of which this one is a dna/protein
2063 if (selectionFromTranslation(seqsel, colsel, hidden, source))
2068 // do we want to thread this ? (contention with seqsel and colsel locks, I
2071 * only copy colsel if there is a real intersection between
2072 * sequence selection and this panel's alignment
2074 boolean repaint = false;
2075 boolean copycolsel = false;
2077 SequenceGroup sgroup = null;
2078 if (seqsel != null && seqsel.getSize() > 0)
2080 if (av.getAlignment() == null)
2082 Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2083 + " ViewId=" + av.getViewId()
2084 + " 's alignment is NULL! returning immediately.");
2087 sgroup = seqsel.intersect(av.getAlignment(),
2088 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2089 if ((sgroup != null && sgroup.getSize() > 0))
2094 if (sgroup != null && sgroup.getSize() > 0)
2096 av.setSelectionGroup(sgroup);
2100 av.setSelectionGroup(null);
2102 av.isSelectionGroupChanged(true);
2107 // the current selection is unset or from a previous message
2108 // so import the new colsel.
2109 if (colsel == null || colsel.isEmpty())
2111 if (av.getColumnSelection() != null)
2113 av.getColumnSelection().clear();
2119 // TODO: shift colSel according to the intersecting sequences
2120 if (av.getColumnSelection() == null)
2122 av.setColumnSelection(new ColumnSelection(colsel));
2126 av.getColumnSelection().setElementsFrom(colsel,
2127 av.getAlignment().getHiddenColumns());
2130 av.isColSelChanged(true);
2135 && av.hasHiddenColumns()
2136 && (av.getAlignment().getHiddenColumns() == null || av
2137 .getAlignment().getHiddenColumns().getHiddenRegions() == null))
2139 System.err.println("Bad things");
2141 if (repaint) // always true!
2143 // probably finessing with multiple redraws here
2144 PaintRefresher.Refresh(this, av.getSequenceSetId());
2145 // ap.paintAlignment(false);
2148 // lastly, update dependent dialogs
2149 if (ap.getCalculationDialog() != null)
2151 ap.getCalculationDialog().validateCalcTypes();
2157 * If this panel is a cdna/protein translation view of the selection source,
2158 * tries to map the source selection to a local one, and returns true. Else
2165 protected boolean selectionFromTranslation(SequenceGroup seqsel,
2166 ColumnSelection colsel, HiddenColumns hidden,
2167 SelectionSource source)
2169 if (!(source instanceof AlignViewportI))
2173 final AlignViewportI sourceAv = (AlignViewportI) source;
2174 if (sourceAv.getCodingComplement() != av
2175 && av.getCodingComplement() != sourceAv)
2181 * Map sequence selection
2183 SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2184 av.setSelectionGroup(sg);
2185 av.isSelectionGroupChanged(true);
2188 * Map column selection
2190 // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2192 ColumnSelection cs = new ColumnSelection();
2193 HiddenColumns hs = new HiddenColumns();
2194 MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2195 av.setColumnSelection(cs);
2196 av.getAlignment().setHiddenColumns(hs);
2198 // lastly, update any dependent dialogs
2199 if (ap.getCalculationDialog() != null)
2201 ap.getCalculationDialog().validateCalcTypes();
2204 PaintRefresher.Refresh(this, av.getSequenceSetId());