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;
87 protected int lastres;
89 protected int startseq;
91 protected AlignViewport av;
93 ScrollThread scrollThread = null;
95 boolean mouseDragging = false;
97 boolean editingSeqs = false;
99 boolean groupEditing = false;
101 // ////////////////////////////////////////
102 // ///Everything below this is for defining the boundary of the rubberband
103 // ////////////////////////////////////////
106 boolean changeEndSeq = false;
108 boolean changeStartSeq = false;
110 boolean changeEndRes = false;
112 boolean changeStartRes = false;
114 SequenceGroup stretchGroup = null;
116 boolean remove = false;
118 Point lastMousePress;
120 boolean mouseWheelPressed = false;
122 StringBuffer keyboardNo1;
124 StringBuffer keyboardNo2;
126 java.net.URL linkImageURL;
128 private final SequenceAnnotationReport seqARep;
130 StringBuilder tooltipText = new StringBuilder();
134 EditCommand editCommand;
136 StructureSelectionManager ssm;
138 SearchResultsI lastSearchResults;
141 * Creates a new SeqPanel object.
148 public SeqPanel(AlignViewport av, AlignmentPanel ap)
150 linkImageURL = getClass().getResource("/images/link.gif");
151 seqARep = new SequenceAnnotationReport(linkImageURL.toString());
152 ToolTipManager.sharedInstance().registerComponent(this);
153 ToolTipManager.sharedInstance().setInitialDelay(0);
154 ToolTipManager.sharedInstance().setDismissDelay(10000);
156 setBackground(Color.white);
158 seqCanvas = new SeqCanvas(ap);
159 setLayout(new BorderLayout());
160 add(seqCanvas, BorderLayout.CENTER);
166 addMouseMotionListener(this);
167 addMouseListener(this);
168 addMouseWheelListener(this);
169 ssm = av.getStructureSelectionManager();
170 ssm.addStructureViewerListener(this);
171 ssm.addSelectionListener(this);
175 int startWrapBlock = -1;
177 int wrappedBlock = -1;
180 * Returns the aligned sequence position (base 0) at the mouse position, or
181 * the closest visible one
186 int findColumn(MouseEvent evt)
191 if (av.getWrapAlignment())
194 int hgap = av.getCharHeight();
195 if (av.getScaleAboveWrapped())
197 hgap += av.getCharHeight();
200 int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
201 + hgap + seqCanvas.getAnnotationHeight();
205 x -= seqCanvas.LABEL_WEST;
207 int cwidth = seqCanvas.getWrappedCanvasWidth(this.getWidth());
213 wrappedBlock = y / cHeight;
214 wrappedBlock += av.getRanges().getStartRes() / cwidth;
216 res = wrappedBlock * cwidth + x / av.getCharWidth();
221 if (x > seqCanvas.getX() + seqCanvas.getWidth())
223 // make sure we calculate relative to visible alignment, rather than
225 x = seqCanvas.getX() + seqCanvas.getWidth();
227 res = (x / av.getCharWidth()) + av.getRanges().getStartRes();
228 if (res > av.getRanges().getEndRes())
231 res = av.getRanges().getEndRes();
235 if (av.hasHiddenColumns())
237 res = av.getAlignment().getHiddenColumns()
238 .adjustForHiddenColumns(res);
245 int findSeq(MouseEvent evt)
250 if (av.getWrapAlignment())
252 int hgap = av.getCharHeight();
253 if (av.getScaleAboveWrapped())
255 hgap += av.getCharHeight();
258 int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
259 + hgap + seqCanvas.getAnnotationHeight();
263 seq = Math.min((y % cHeight) / av.getCharHeight(), av.getAlignment()
268 seq = Math.min((y / av.getCharHeight())
269 + av.getRanges().getStartSeq(),
271 .getAlignment().getHeight() - 1);
278 * When all of a sequence of edits are complete, put the resulting edit list
279 * on the history stack (undo list), and reset flags for editing in progress.
285 if (editCommand != null && editCommand.getSize() > 0)
287 ap.alignFrame.addHistoryItem(editCommand);
288 av.firePropertyChange("alignment", null, av.getAlignment()
294 * Tidy up come what may...
299 groupEditing = false;
308 seqCanvas.cursorY = getKeyboardNo1() - 1;
312 void setCursorColumn()
314 seqCanvas.cursorX = getKeyboardNo1() - 1;
318 void setCursorRowAndColumn()
320 if (keyboardNo2 == null)
322 keyboardNo2 = new StringBuffer();
326 seqCanvas.cursorX = getKeyboardNo1() - 1;
327 seqCanvas.cursorY = getKeyboardNo2() - 1;
332 void setCursorPosition()
334 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
336 seqCanvas.cursorX = sequence.findIndex(getKeyboardNo1()) - 1;
340 void moveCursor(int dx, int dy)
342 seqCanvas.cursorX += dx;
343 seqCanvas.cursorY += dy;
345 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
347 if (av.hasHiddenColumns()
348 && !hidden.isVisible(seqCanvas.cursorX))
350 int original = seqCanvas.cursorX - dx;
351 int maxWidth = av.getAlignment().getWidth();
353 while (!hidden.isVisible(seqCanvas.cursorX)
354 && seqCanvas.cursorX < maxWidth && seqCanvas.cursorX > 0)
356 seqCanvas.cursorX += dx;
359 if (seqCanvas.cursorX >= maxWidth
360 || !hidden.isVisible(seqCanvas.cursorX))
362 seqCanvas.cursorX = original;
369 void scrollToVisible()
371 if (seqCanvas.cursorX < 0)
373 seqCanvas.cursorX = 0;
375 else if (seqCanvas.cursorX > av.getAlignment().getWidth() - 1)
377 seqCanvas.cursorX = av.getAlignment().getWidth() - 1;
380 if (seqCanvas.cursorY < 0)
382 seqCanvas.cursorY = 0;
384 else if (seqCanvas.cursorY > av.getAlignment().getHeight() - 1)
386 seqCanvas.cursorY = av.getAlignment().getHeight() - 1;
390 if (av.getWrapAlignment())
392 ap.scrollToWrappedVisible(seqCanvas.cursorX);
396 while (seqCanvas.cursorY < av.getRanges().getStartSeq())
400 while (seqCanvas.cursorY > av.getRanges().getEndSeq())
404 if (!av.getWrapAlignment())
406 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
407 while (seqCanvas.cursorX < hidden.adjustForHiddenColumns(av
408 .getRanges().getStartRes()))
410 if (!ap.scrollRight(false))
415 while (seqCanvas.cursorX > hidden.adjustForHiddenColumns(av
416 .getRanges().getEndRes()))
418 if (!ap.scrollRight(true))
425 setStatusMessage(av.getAlignment().getSequenceAt(seqCanvas.cursorY),
426 seqCanvas.cursorX, seqCanvas.cursorY);
431 void setSelectionAreaAtCursor(boolean topLeft)
433 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
435 if (av.getSelectionGroup() != null)
437 SequenceGroup sg = av.getSelectionGroup();
438 // Find the top and bottom of this group
439 int min = av.getAlignment().getHeight(), max = 0;
440 for (int i = 0; i < sg.getSize(); i++)
442 int index = av.getAlignment().findIndex(sg.getSequenceAt(i));
457 sg.setStartRes(seqCanvas.cursorX);
458 if (sg.getEndRes() < seqCanvas.cursorX)
460 sg.setEndRes(seqCanvas.cursorX);
463 min = seqCanvas.cursorY;
467 sg.setEndRes(seqCanvas.cursorX);
468 if (sg.getStartRes() > seqCanvas.cursorX)
470 sg.setStartRes(seqCanvas.cursorX);
473 max = seqCanvas.cursorY + 1;
478 // Only the user can do this
479 av.setSelectionGroup(null);
483 // Now add any sequences between min and max
484 sg.getSequences(null).clear();
485 for (int i = min; i < max; i++)
487 sg.addSequence(av.getAlignment().getSequenceAt(i), false);
492 if (av.getSelectionGroup() == null)
494 SequenceGroup sg = new SequenceGroup();
495 sg.setStartRes(seqCanvas.cursorX);
496 sg.setEndRes(seqCanvas.cursorX);
497 sg.addSequence(sequence, false);
498 av.setSelectionGroup(sg);
501 ap.paintAlignment(false);
505 void insertGapAtCursor(boolean group)
507 groupEditing = group;
508 startseq = seqCanvas.cursorY;
509 lastres = seqCanvas.cursorX;
510 editSequence(true, false, seqCanvas.cursorX + getKeyboardNo1());
514 void deleteGapAtCursor(boolean group)
516 groupEditing = group;
517 startseq = seqCanvas.cursorY;
518 lastres = seqCanvas.cursorX + getKeyboardNo1();
519 editSequence(false, false, seqCanvas.cursorX);
523 void insertNucAtCursor(boolean group, String nuc)
525 // TODO not called - delete?
526 groupEditing = group;
527 startseq = seqCanvas.cursorY;
528 lastres = seqCanvas.cursorX;
529 editSequence(false, true, seqCanvas.cursorX + getKeyboardNo1());
533 void numberPressed(char value)
535 if (keyboardNo1 == null)
537 keyboardNo1 = new StringBuffer();
540 if (keyboardNo2 != null)
542 keyboardNo2.append(value);
546 keyboardNo1.append(value);
554 if (keyboardNo1 != null)
556 int value = Integer.parseInt(keyboardNo1.toString());
560 } catch (Exception x)
571 if (keyboardNo2 != null)
573 int value = Integer.parseInt(keyboardNo2.toString());
577 } catch (Exception x)
591 public void mouseReleased(MouseEvent evt)
593 mouseDragging = false;
594 mouseWheelPressed = false;
596 if (evt.isPopupTrigger()) // Windows: mouseReleased
605 doMouseReleasedDefineMode(evt);
619 public void mousePressed(MouseEvent evt)
621 lastMousePress = evt.getPoint();
623 if (SwingUtilities.isMiddleMouseButton(evt))
625 mouseWheelPressed = true;
629 boolean isControlDown = Platform.isControlDown(evt);
630 if (evt.isShiftDown() || isControlDown)
640 doMousePressedDefineMode(evt);
644 int seq = findSeq(evt);
645 int res = findColumn(evt);
647 if (seq < 0 || res < 0)
652 if ((seq < av.getAlignment().getHeight())
653 && (res < av.getAlignment().getSequenceAt(seq).getLength()))
670 public void mouseOverSequence(SequenceI sequence, int index, int pos)
672 String tmp = sequence.hashCode() + " " + index + " " + pos;
674 if (lastMessage == null || !lastMessage.equals(tmp))
676 // System.err.println("mouseOver Sequence: "+tmp);
677 ssm.mouseOverSequence(sequence, index, pos, av);
683 * Highlight the mapped region described by the search results object (unless
684 * unchanged). This supports highlight of protein while mousing over linked
685 * cDNA and vice versa. The status bar is also updated to show the location of
686 * the start of the highlighted region.
689 public void highlightSequence(SearchResultsI results)
691 if (results == null || results.equals(lastSearchResults))
695 lastSearchResults = results;
697 if (av.isFollowHighlight())
700 * if scrollToPosition requires a scroll adjustment, this flag prevents
701 * another scroll event being propagated back to the originator
703 * @see AlignmentPanel#adjustmentValueChanged
705 ap.setDontScrollComplement(true);
706 if (ap.scrollToPosition(results, false))
708 seqCanvas.revalidate();
711 setStatusMessage(results);
712 seqCanvas.highlightSearchResults(results);
716 public VamsasSource getVamsasSource()
718 return this.ap == null ? null : this.ap.av;
722 public void updateColours(SequenceI seq, int index)
724 System.out.println("update the seqPanel colours");
735 public void mouseMoved(MouseEvent evt)
739 // This is because MacOSX creates a mouseMoved
740 // If control is down, other platforms will not.
744 final int column = findColumn(evt);
745 int seq = findSeq(evt);
746 if (column < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
751 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
753 if (column >= sequence.getLength())
759 * set status bar message, returning residue position in sequence
761 final int pos = setStatusMessage(sequence, column, seq);
762 if (ssm != null && pos > -1)
764 mouseOverSequence(sequence, column, pos);
767 tooltipText.setLength(6); // Cuts the buffer back to <html>
769 SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
772 for (int g = 0; g < groups.length; g++)
774 if (groups[g].getStartRes() <= column
775 && groups[g].getEndRes() >= column)
777 if (!groups[g].getName().startsWith("JTreeGroup")
778 && !groups[g].getName().startsWith("JGroup"))
780 tooltipText.append(groups[g].getName());
783 if (groups[g].getDescription() != null)
785 tooltipText.append(": " + groups[g].getDescription());
791 if (av.isShowSequenceFeatures())
793 List<SequenceFeature> features = ap.getFeatureRenderer()
794 .findFeaturesAtRes(sequence.getDatasetSequence(), pos);
795 seqARep.appendFeatures(tooltipText, pos, features,
796 this.ap.getSeqPanel().seqCanvas.fr.getMinMax());
798 if (tooltipText.length() == 6) // <html>
800 setToolTipText(null);
805 if (lastTooltip == null
806 || !lastTooltip.equals(tooltipText.toString()))
808 String formatedTooltipText = JvSwingUtils.wrapTooltip(true,
809 tooltipText.toString());
810 // String formatedTooltipText = tooltipText.toString();
811 setToolTipText(formatedTooltipText);
812 lastTooltip = tooltipText.toString();
819 private Point lastp = null;
824 * @see javax.swing.JComponent#getToolTipLocation(java.awt.event.MouseEvent)
827 public Point getToolTipLocation(MouseEvent event)
829 int x = event.getX(), w = getWidth();
830 int wdth = (w - x < 200) ? -(w / 2) : 5; // switch sides when tooltip is too
833 if (!event.isShiftDown() || p == null)
835 p = (tooltipText != null && tooltipText.length() > 6) ? new Point(
836 event.getX() + wdth, event.getY() - 20) : null;
839 * TODO: try to modify position region is not obcured by tooltip
847 * set when the current UI interaction has resulted in a change that requires
848 * overview shading to be recalculated. this could be changed to something
849 * more expressive that indicates what actually has changed, so selective
850 * redraws can be applied
852 private boolean needOverviewUpdate = false; // TODO: refactor to avcontroller
855 * set if av.getSelectionGroup() refers to a group that is defined on the
856 * alignment view, rather than a transient selection
858 // private boolean editingDefinedGroup = false; // TODO: refactor to
859 // avcontroller or viewModel
862 * Sets the status message in alignment panel, showing the sequence number
863 * (index) and id, residue and residue position for the given sequence and
864 * column position. Returns the calculated residue position in the sequence.
867 * aligned sequence object
871 * index of sequence in alignment
872 * @return position of res in sequence
874 int setStatusMessage(SequenceI sequence, final int column, int seq)
876 StringBuilder text = new StringBuilder(32);
879 * Sequence number (if known), and sequence name.
881 String seqno = seq == -1 ? "" : " " + (seq + 1);
882 text.append("Sequence").append(seqno).append(" ID: ")
883 .append(sequence.getName());
885 String residue = null;
887 * Try to translate the display character to residue name (null for gap).
889 final String displayChar = String.valueOf(sequence.getCharAt(column));
890 if (av.getAlignment().isNucleotide())
892 residue = ResidueProperties.nucleotideName.get(displayChar);
895 text.append(" Nucleotide: ").append(residue);
900 residue = "X".equalsIgnoreCase(displayChar) ? "X" : ("*"
901 .equals(displayChar) ? "STOP" : ResidueProperties.aa2Triplet
905 text.append(" Residue: ").append(residue);
910 pos = sequence.findPosition(column);
913 text.append(" (").append(Integer.toString(pos)).append(")");
915 ap.alignFrame.statusBar.setText(text.toString());
920 * Set the status bar message to highlight the first matched position in
925 private void setStatusMessage(SearchResultsI results)
927 AlignmentI al = this.av.getAlignment();
928 int sequenceIndex = al.findIndex(results);
929 if (sequenceIndex == -1)
933 SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
934 for (SearchResultMatchI m : results.getResults())
936 SequenceI seq = m.getSequence();
937 if (seq.getDatasetSequence() != null)
939 seq = seq.getDatasetSequence();
945 * Convert position in sequence (base 1) to sequence character array
948 int start = m.getStart() - m.getSequence().getStart();
949 setStatusMessage(seq, start, sequenceIndex);
959 public void mouseDragged(MouseEvent evt)
961 if (mouseWheelPressed)
963 boolean inSplitFrame = ap.av.getCodingComplement() != null;
964 boolean copyChanges = inSplitFrame && av.isProteinFontAsCdna();
966 int oldWidth = av.getCharWidth();
968 // Which is bigger, left-right or up-down?
969 if (Math.abs(evt.getY() - lastMousePress.getY()) > Math.abs(evt
970 .getX() - lastMousePress.getX()))
973 * on drag up or down, decrement or increment font size
975 int fontSize = av.font.getSize();
976 boolean fontChanged = false;
978 if (evt.getY() < lastMousePress.getY())
983 else if (evt.getY() > lastMousePress.getY())
996 Font newFont = new Font(av.font.getName(), av.font.getStyle(),
998 av.setFont(newFont, true);
999 av.setCharWidth(oldWidth);
1003 ap.av.getCodingComplement().setFont(newFont, true);
1004 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1005 .getSplitViewContainer();
1006 splitFrame.adjustLayout();
1007 splitFrame.repaint();
1014 * on drag left or right, decrement or increment character width
1017 if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
1019 newWidth = av.getCharWidth() - 1;
1020 av.setCharWidth(newWidth);
1022 else if (evt.getX() > lastMousePress.getX())
1024 newWidth = av.getCharWidth() + 1;
1025 av.setCharWidth(newWidth);
1029 ap.paintAlignment(false);
1033 * need to ensure newWidth is set on cdna, regardless of which
1034 * panel the mouse drag happened in; protein will compute its
1035 * character width as 1:1 or 3:1
1037 av.getCodingComplement().setCharWidth(newWidth);
1038 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1039 .getSplitViewContainer();
1040 splitFrame.adjustLayout();
1041 splitFrame.repaint();
1046 FontMetrics fm = getFontMetrics(av.getFont());
1047 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1049 lastMousePress = evt.getPoint();
1056 doMouseDraggedDefineMode(evt);
1060 int res = findColumn(evt);
1067 if ((lastres == -1) || (lastres == res))
1072 if ((res < av.getAlignment().getWidth()) && (res < lastres))
1074 // dragLeft, delete gap
1075 editSequence(false, false, res);
1079 editSequence(true, false, res);
1082 mouseDragging = true;
1083 if (scrollThread != null)
1085 scrollThread.setEvent(evt);
1089 // TODO: Make it more clever than many booleans
1090 synchronized void editSequence(boolean insertGap, boolean editSeq,
1094 int fixedRight = -1;
1095 boolean fixedColumns = false;
1096 SequenceGroup sg = av.getSelectionGroup();
1098 SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1100 // No group, but the sequence may represent a group
1101 if (!groupEditing && av.hasHiddenRows())
1103 if (av.isHiddenRepSequence(seq))
1105 sg = av.getRepresentedSequences(seq);
1106 groupEditing = true;
1110 StringBuilder message = new StringBuilder(64);
1113 message.append("Edit group:");
1114 if (editCommand == null)
1116 editCommand = new EditCommand(
1117 MessageManager.getString("action.edit_group"));
1122 message.append("Edit sequence: " + seq.getName());
1123 String label = seq.getName();
1124 if (label.length() > 10)
1126 label = label.substring(0, 10);
1128 if (editCommand == null)
1130 editCommand = new EditCommand(MessageManager.formatMessage(
1131 "label.edit_params", new String[] { label }));
1137 message.append(" insert ");
1141 message.append(" delete ");
1144 message.append(Math.abs(startres - lastres) + " gaps.");
1145 ap.alignFrame.statusBar.setText(message.toString());
1147 // Are we editing within a selection group?
1149 || (sg != null && sg.getSequences(av.getHiddenRepSequences())
1152 fixedColumns = true;
1154 // sg might be null as the user may only see 1 sequence,
1155 // but the sequence represents a group
1158 if (!av.isHiddenRepSequence(seq))
1163 sg = av.getRepresentedSequences(seq);
1166 fixedLeft = sg.getStartRes();
1167 fixedRight = sg.getEndRes();
1169 if ((startres < fixedLeft && lastres >= fixedLeft)
1170 || (startres >= fixedLeft && lastres < fixedLeft)
1171 || (startres > fixedRight && lastres <= fixedRight)
1172 || (startres <= fixedRight && lastres > fixedRight))
1178 if (fixedLeft > startres)
1180 fixedRight = fixedLeft - 1;
1183 else if (fixedRight < startres)
1185 fixedLeft = fixedRight;
1190 if (av.hasHiddenColumns())
1192 fixedColumns = true;
1193 int y1 = av.getAlignment().getHiddenColumns()
1194 .getHiddenBoundaryLeft(startres);
1195 int y2 = av.getAlignment().getHiddenColumns()
1196 .getHiddenBoundaryRight(startres);
1198 if ((insertGap && startres > y1 && lastres < y1)
1199 || (!insertGap && startres < y2 && lastres > y2))
1205 // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1206 // Selection spans a hidden region
1207 if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1215 fixedRight = y2 - 1;
1222 List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1223 int g, groupSize = vseqs.size();
1224 SequenceI[] groupSeqs = new SequenceI[groupSize];
1225 for (g = 0; g < groupSeqs.length; g++)
1227 groupSeqs[g] = vseqs.get(g);
1233 // If the user has selected the whole sequence, and is dragging to
1234 // the right, we can still extend the alignment and selectionGroup
1235 if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1236 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1238 sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1239 fixedRight = sg.getEndRes();
1242 // Is it valid with fixed columns??
1243 // Find the next gap before the end
1244 // of the visible region boundary
1245 boolean blank = false;
1246 for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1250 for (g = 0; g < groupSize; g++)
1252 for (int j = 0; j < startres - lastres; j++)
1254 if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1269 if (sg.getSize() == av.getAlignment().getHeight())
1271 if ((av.hasHiddenColumns() && startres < av.getAlignment()
1272 .getHiddenColumns().getHiddenBoundaryRight(startres)))
1278 int alWidth = av.getAlignment().getWidth();
1279 if (av.hasHiddenRows())
1281 int hwidth = av.getAlignment().getHiddenSequences()
1283 if (hwidth > alWidth)
1288 // We can still insert gaps if the selectionGroup
1289 // contains all the sequences
1290 sg.setEndRes(sg.getEndRes() + startres - lastres);
1291 fixedRight = alWidth + startres - lastres;
1302 else if (!insertGap)
1304 // / Are we able to delete?
1305 // ie are all columns blank?
1307 for (g = 0; g < groupSize; g++)
1309 for (int j = startres; j < lastres; j++)
1311 if (groupSeqs[g].getLength() <= j)
1316 if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1318 // Not a gap, block edit not valid
1328 // dragging to the right
1329 if (fixedColumns && fixedRight != -1)
1331 for (int j = lastres; j < startres; j++)
1333 insertChar(j, groupSeqs, fixedRight);
1338 appendEdit(Action.INSERT_GAP, groupSeqs, startres, startres
1344 // dragging to the left
1345 if (fixedColumns && fixedRight != -1)
1347 for (int j = lastres; j > startres; j--)
1349 deleteChar(startres, groupSeqs, fixedRight);
1354 appendEdit(Action.DELETE_GAP, groupSeqs, startres, lastres
1361 // ///Editing a single sequence///////////
1365 // dragging to the right
1366 if (fixedColumns && fixedRight != -1)
1368 for (int j = lastres; j < startres; j++)
1370 insertChar(j, new SequenceI[] { seq }, fixedRight);
1375 appendEdit(Action.INSERT_GAP, new SequenceI[] { seq }, lastres,
1376 startres - lastres);
1383 // dragging to the left
1384 if (fixedColumns && fixedRight != -1)
1386 for (int j = lastres; j > startres; j--)
1388 if (!Comparison.isGap(seq.getCharAt(startres)))
1393 deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1398 // could be a keyboard edit trying to delete none gaps
1400 for (int m = startres; m < lastres; m++)
1402 if (!Comparison.isGap(seq.getCharAt(m)))
1411 appendEdit(Action.DELETE_GAP, new SequenceI[] { seq },
1417 {// insertGap==false AND editSeq==TRUE;
1418 if (fixedColumns && fixedRight != -1)
1420 for (int j = lastres; j < startres; j++)
1422 insertChar(j, new SequenceI[] { seq }, fixedRight);
1427 appendEdit(Action.INSERT_NUC, new SequenceI[] { seq }, lastres,
1428 startres - lastres);
1435 seqCanvas.repaint();
1438 void insertChar(int j, SequenceI[] seq, int fixedColumn)
1440 int blankColumn = fixedColumn;
1441 for (int s = 0; s < seq.length; s++)
1443 // Find the next gap before the end of the visible region boundary
1444 // If lastCol > j, theres a boundary after the gap insertion
1446 for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1448 if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1450 // Theres a space, so break and insert the gap
1455 if (blankColumn <= j)
1457 blankColumn = fixedColumn;
1463 appendEdit(Action.DELETE_GAP, seq, blankColumn, 1);
1465 appendEdit(Action.INSERT_GAP, seq, j, 1);
1470 * Helper method to add and perform one edit action.
1477 protected void appendEdit(Action action, SequenceI[] seq, int pos,
1481 final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1482 av.getAlignment().getGapCharacter());
1484 editCommand.appendEdit(edit, av.getAlignment(), true, null);
1487 void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1490 appendEdit(Action.DELETE_GAP, seq, j, 1);
1492 appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1);
1502 public void mouseEntered(MouseEvent e)
1509 if (scrollThread != null)
1511 scrollThread.running = false;
1512 scrollThread = null;
1523 public void mouseExited(MouseEvent e)
1525 if (av.getWrapAlignment())
1532 scrollThread = new ScrollThread();
1537 * Handler for double-click on a position with one or more sequence features.
1538 * Opens the Amend Features dialog to allow feature details to be amended, or
1539 * the feature deleted.
1542 public void mouseClicked(MouseEvent evt)
1544 SequenceGroup sg = null;
1545 SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
1546 if (evt.getClickCount() > 1)
1548 sg = av.getSelectionGroup();
1549 if (sg != null && sg.getSize() == 1
1550 && sg.getEndRes() - sg.getStartRes() < 2)
1552 av.setSelectionGroup(null);
1555 List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1556 .findFeaturesAtRes(sequence.getDatasetSequence(),
1557 sequence.findPosition(findColumn(evt)));
1559 if (!features.isEmpty())
1562 * highlight the first feature at the position on the alignment
1564 SearchResultsI highlight = new SearchResults();
1565 highlight.addResult(sequence, features.get(0).getBegin(), features
1567 seqCanvas.highlightSearchResults(highlight);
1570 * open the Amend Features dialog; clear highlighting afterwards,
1571 * whether changes were made or not
1573 List<SequenceI> seqs = Collections.singletonList(sequence);
1574 seqCanvas.getFeatureRenderer().amendFeatures(seqs, features, false,
1576 seqCanvas.highlightSearchResults(null);
1582 public void mouseWheelMoved(MouseWheelEvent e)
1585 if (e.getWheelRotation() > 0)
1587 if (e.isShiftDown())
1589 ap.scrollRight(true);
1599 if (e.isShiftDown())
1601 ap.scrollRight(false);
1608 // TODO Update tooltip for new position.
1617 public void doMousePressedDefineMode(MouseEvent evt)
1619 final int res = findColumn(evt);
1620 final int seq = findSeq(evt);
1622 needOverviewUpdate = false;
1624 startWrapBlock = wrappedBlock;
1626 if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1628 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
1629 .getString("label.cannot_edit_annotations_in_wrapped_view"),
1630 MessageManager.getString("label.wrapped_view_no_edit"),
1631 JvOptionPane.WARNING_MESSAGE);
1635 if (seq < 0 || res < 0)
1640 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1642 if ((sequence == null) || (res > sequence.getLength()))
1647 stretchGroup = av.getSelectionGroup();
1649 if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1651 stretchGroup = av.getAlignment().findGroup(sequence, res);
1652 if (stretchGroup != null)
1654 // only update the current selection if the popup menu has a group to
1656 av.setSelectionGroup(stretchGroup);
1660 if (evt.isPopupTrigger()) // Mac: mousePressed
1667 * defer right-mouse click handling to mouseReleased on Windows
1668 * (where isPopupTrigger() will answer true)
1669 * NB isRightMouseButton is also true for Cmd-click on Mac
1671 if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1678 seqCanvas.cursorX = findColumn(evt);
1679 seqCanvas.cursorY = findSeq(evt);
1680 seqCanvas.repaint();
1684 if (stretchGroup == null)
1686 // Only if left mouse button do we want to change group sizes
1688 // define a new group here
1689 SequenceGroup sg = new SequenceGroup();
1690 sg.setStartRes(res);
1692 sg.addSequence(sequence, false);
1693 av.setSelectionGroup(sg);
1696 if (av.getConservationSelected())
1698 SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1702 if (av.getAbovePIDThreshold())
1704 SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1707 // TODO: stretchGroup will always be not null. Is this a merge error ?
1708 if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1710 // Edit end res position of selected group
1711 changeEndRes = true;
1713 else if ((stretchGroup != null)
1714 && (stretchGroup.getStartRes() == res))
1716 // Edit end res position of selected group
1717 changeStartRes = true;
1719 stretchGroup.getWidth();
1722 seqCanvas.repaint();
1726 * Build and show a pop-up menu at the right-click mouse position
1732 void showPopupMenu(MouseEvent evt)
1734 final int res = findColumn(evt);
1735 final int seq = findSeq(evt);
1736 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1737 List<SequenceFeature> allFeatures = ap.getFeatureRenderer()
1738 .findFeaturesAtRes(sequence.getDatasetSequence(),
1739 sequence.findPosition(res));
1740 List<String> links = new ArrayList<String>();
1741 for (SequenceFeature sf : allFeatures)
1743 if (sf.links != null)
1745 for (String link : sf.links)
1752 PopupMenu pop = new PopupMenu(ap, null, links);
1753 pop.show(this, evt.getX(), evt.getY());
1762 public void doMouseReleasedDefineMode(MouseEvent evt)
1764 if (stretchGroup == null)
1768 // always do this - annotation has own state
1769 // but defer colourscheme update until hidden sequences are passed in
1770 boolean vischange = stretchGroup.recalcConservation(true);
1771 needOverviewUpdate |= vischange && av.isSelectionDefinedGroup();
1772 if (stretchGroup.cs != null)
1774 stretchGroup.cs.alignmentChanged(stretchGroup,
1775 av.getHiddenRepSequences());
1777 ResidueShaderI groupColourScheme = stretchGroup.getGroupColourScheme();
1778 String name = stretchGroup.getName();
1779 if (stretchGroup.cs.conservationApplied())
1781 SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1783 if (stretchGroup.cs.getThreshold() > 0)
1785 SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1788 PaintRefresher.Refresh(this, av.getSequenceSetId());
1789 ap.paintAlignment(needOverviewUpdate);
1790 needOverviewUpdate = false;
1791 changeEndRes = false;
1792 changeStartRes = false;
1793 stretchGroup = null;
1803 public void doMouseDraggedDefineMode(MouseEvent evt)
1805 int res = findColumn(evt);
1806 int y = findSeq(evt);
1808 if (wrappedBlock != startWrapBlock)
1813 if (stretchGroup == null)
1818 if (res >= av.getAlignment().getWidth())
1820 res = av.getAlignment().getWidth() - 1;
1823 if (stretchGroup.getEndRes() == res)
1825 // Edit end res position of selected group
1826 changeEndRes = true;
1828 else if (stretchGroup.getStartRes() == res)
1830 // Edit start res position of selected group
1831 changeStartRes = true;
1834 if (res < av.getRanges().getStartRes())
1836 res = av.getRanges().getStartRes();
1841 if (res > (stretchGroup.getStartRes() - 1))
1843 stretchGroup.setEndRes(res);
1844 needOverviewUpdate |= av.isSelectionDefinedGroup();
1847 else if (changeStartRes)
1849 if (res < (stretchGroup.getEndRes() + 1))
1851 stretchGroup.setStartRes(res);
1852 needOverviewUpdate |= av.isSelectionDefinedGroup();
1856 int dragDirection = 0;
1862 else if (y < oldSeq)
1867 while ((y != oldSeq) && (oldSeq > -1)
1868 && (y < av.getAlignment().getHeight()))
1870 // This routine ensures we don't skip any sequences, as the
1871 // selection is quite slow.
1872 Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1874 oldSeq += dragDirection;
1881 Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1883 if (stretchGroup.getSequences(null).contains(nextSeq))
1885 stretchGroup.deleteSequence(seq, false);
1886 needOverviewUpdate |= av.isSelectionDefinedGroup();
1892 stretchGroup.addSequence(seq, false);
1895 stretchGroup.addSequence(nextSeq, false);
1896 needOverviewUpdate |= av.isSelectionDefinedGroup();
1905 mouseDragging = true;
1907 if (scrollThread != null)
1909 scrollThread.setEvent(evt);
1912 seqCanvas.repaint();
1915 void scrollCanvas(MouseEvent evt)
1919 if (scrollThread != null)
1921 scrollThread.running = false;
1922 scrollThread = null;
1924 mouseDragging = false;
1928 if (scrollThread == null)
1930 scrollThread = new ScrollThread();
1933 mouseDragging = true;
1934 scrollThread.setEvent(evt);
1939 // this class allows scrolling off the bottom of the visible alignment
1940 class ScrollThread extends Thread
1944 boolean running = false;
1946 public ScrollThread()
1951 public void setEvent(MouseEvent e)
1956 public void stopScrolling()
1970 if (mouseDragging && (evt.getY() < 0)
1971 && (av.getRanges().getStartSeq() > 0))
1973 running = ap.scrollUp(true);
1976 if (mouseDragging && (evt.getY() >= getHeight())
1977 && (av.getAlignment().getHeight() > av.getRanges()
1980 running = ap.scrollUp(false);
1983 if (mouseDragging && (evt.getX() < 0))
1985 running = ap.scrollRight(false);
1987 else if (mouseDragging && (evt.getX() >= getWidth()))
1989 running = ap.scrollRight(true);
1996 } catch (Exception ex)
2004 * modify current selection according to a received message.
2007 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
2008 HiddenColumns hidden, SelectionSource source)
2010 // TODO: fix this hack - source of messages is align viewport, but SeqPanel
2011 // handles selection messages...
2012 // TODO: extend config options to allow user to control if selections may be
2013 // shared between viewports.
2014 boolean iSentTheSelection = (av == source || (source instanceof AlignViewport && ((AlignmentViewport) source)
2015 .getSequenceSetId().equals(av.getSequenceSetId())));
2017 if (iSentTheSelection)
2019 // respond to our own event by updating dependent dialogs
2020 if (ap.getCalculationDialog() != null)
2022 ap.getCalculationDialog().validateCalcTypes();
2025 // process further ?
2026 if (!av.followSelection)
2033 * Ignore the selection if there is one of our own pending.
2035 if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
2041 * Check for selection in a view of which this one is a dna/protein
2044 if (selectionFromTranslation(seqsel, colsel, hidden, source))
2049 // do we want to thread this ? (contention with seqsel and colsel locks, I
2052 * only copy colsel if there is a real intersection between
2053 * sequence selection and this panel's alignment
2055 boolean repaint = false;
2056 boolean copycolsel = false;
2058 SequenceGroup sgroup = null;
2059 if (seqsel != null && seqsel.getSize() > 0)
2061 if (av.getAlignment() == null)
2063 Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2064 + " ViewId=" + av.getViewId()
2065 + " 's alignment is NULL! returning immediately.");
2068 sgroup = seqsel.intersect(av.getAlignment(),
2069 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2070 if ((sgroup != null && sgroup.getSize() > 0))
2075 if (sgroup != null && sgroup.getSize() > 0)
2077 av.setSelectionGroup(sgroup);
2081 av.setSelectionGroup(null);
2083 av.isSelectionGroupChanged(true);
2088 // the current selection is unset or from a previous message
2089 // so import the new colsel.
2090 if (colsel == null || colsel.isEmpty())
2092 if (av.getColumnSelection() != null)
2094 av.getColumnSelection().clear();
2100 // TODO: shift colSel according to the intersecting sequences
2101 if (av.getColumnSelection() == null)
2103 av.setColumnSelection(new ColumnSelection(colsel));
2107 av.getColumnSelection().setElementsFrom(colsel,
2108 av.getAlignment().getHiddenColumns());
2111 av.isColSelChanged(true);
2116 && av.hasHiddenColumns()
2117 && (av.getAlignment().getHiddenColumns() == null || av
2118 .getAlignment().getHiddenColumns().getHiddenRegions() == null))
2120 System.err.println("Bad things");
2122 if (repaint) // always true!
2124 // probably finessing with multiple redraws here
2125 PaintRefresher.Refresh(this, av.getSequenceSetId());
2126 // ap.paintAlignment(false);
2129 // lastly, update dependent dialogs
2130 if (ap.getCalculationDialog() != null)
2132 ap.getCalculationDialog().validateCalcTypes();
2138 * If this panel is a cdna/protein translation view of the selection source,
2139 * tries to map the source selection to a local one, and returns true. Else
2146 protected boolean selectionFromTranslation(SequenceGroup seqsel,
2147 ColumnSelection colsel, HiddenColumns hidden,
2148 SelectionSource source)
2150 if (!(source instanceof AlignViewportI))
2154 final AlignViewportI sourceAv = (AlignViewportI) source;
2155 if (sourceAv.getCodingComplement() != av
2156 && av.getCodingComplement() != sourceAv)
2162 * Map sequence selection
2164 SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2165 av.setSelectionGroup(sg);
2166 av.isSelectionGroupChanged(true);
2169 * Map column selection
2171 // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2173 ColumnSelection cs = new ColumnSelection();
2174 HiddenColumns hs = new HiddenColumns();
2175 MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2176 av.setColumnSelection(cs);
2177 av.getAlignment().setHiddenColumns(hs);
2179 // lastly, update any dependent dialogs
2180 if (ap.getCalculationDialog() != null)
2182 ap.getCalculationDialog().validateCalcTypes();
2185 PaintRefresher.Refresh(this, av.getSequenceSetId());