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.labelWidthWest;
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 av.getRanges().scrollToWrappedVisible(seqCanvas.cursorX);
409 av.getRanges().scrollToVisible(seqCanvas.cursorX, seqCanvas.cursorY);
411 setStatusMessage(av.getAlignment().getSequenceAt(seqCanvas.cursorY),
412 seqCanvas.cursorX, seqCanvas.cursorY);
417 void setSelectionAreaAtCursor(boolean topLeft)
419 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
421 if (av.getSelectionGroup() != null)
423 SequenceGroup sg = av.getSelectionGroup();
424 // Find the top and bottom of this group
425 int min = av.getAlignment().getHeight(), max = 0;
426 for (int i = 0; i < sg.getSize(); i++)
428 int index = av.getAlignment().findIndex(sg.getSequenceAt(i));
443 sg.setStartRes(seqCanvas.cursorX);
444 if (sg.getEndRes() < seqCanvas.cursorX)
446 sg.setEndRes(seqCanvas.cursorX);
449 min = seqCanvas.cursorY;
453 sg.setEndRes(seqCanvas.cursorX);
454 if (sg.getStartRes() > seqCanvas.cursorX)
456 sg.setStartRes(seqCanvas.cursorX);
459 max = seqCanvas.cursorY + 1;
464 // Only the user can do this
465 av.setSelectionGroup(null);
469 // Now add any sequences between min and max
470 sg.getSequences(null).clear();
471 for (int i = min; i < max; i++)
473 sg.addSequence(av.getAlignment().getSequenceAt(i), false);
478 if (av.getSelectionGroup() == null)
480 SequenceGroup sg = new SequenceGroup();
481 sg.setStartRes(seqCanvas.cursorX);
482 sg.setEndRes(seqCanvas.cursorX);
483 sg.addSequence(sequence, false);
484 av.setSelectionGroup(sg);
487 ap.paintAlignment(false);
491 void insertGapAtCursor(boolean group)
493 groupEditing = group;
494 startseq = seqCanvas.cursorY;
495 lastres = seqCanvas.cursorX;
496 editSequence(true, false, seqCanvas.cursorX + getKeyboardNo1());
500 void deleteGapAtCursor(boolean group)
502 groupEditing = group;
503 startseq = seqCanvas.cursorY;
504 lastres = seqCanvas.cursorX + getKeyboardNo1();
505 editSequence(false, false, seqCanvas.cursorX);
509 void insertNucAtCursor(boolean group, String nuc)
511 // TODO not called - delete?
512 groupEditing = group;
513 startseq = seqCanvas.cursorY;
514 lastres = seqCanvas.cursorX;
515 editSequence(false, true, seqCanvas.cursorX + getKeyboardNo1());
519 void numberPressed(char value)
521 if (keyboardNo1 == null)
523 keyboardNo1 = new StringBuffer();
526 if (keyboardNo2 != null)
528 keyboardNo2.append(value);
532 keyboardNo1.append(value);
540 if (keyboardNo1 != null)
542 int value = Integer.parseInt(keyboardNo1.toString());
546 } catch (Exception x)
557 if (keyboardNo2 != null)
559 int value = Integer.parseInt(keyboardNo2.toString());
563 } catch (Exception x)
577 public void mouseReleased(MouseEvent evt)
579 boolean didDrag = mouseDragging; // did we come here after a drag
580 mouseDragging = false;
581 mouseWheelPressed = false;
583 if (evt.isPopupTrigger()) // Windows: mouseReleased
592 doMouseReleasedDefineMode(evt, didDrag);
606 public void mousePressed(MouseEvent evt)
608 lastMousePress = evt.getPoint();
610 if (SwingUtilities.isMiddleMouseButton(evt))
612 mouseWheelPressed = true;
616 boolean isControlDown = Platform.isControlDown(evt);
617 if (evt.isShiftDown() || isControlDown)
627 doMousePressedDefineMode(evt);
631 int seq = findSeq(evt);
632 int res = findColumn(evt);
634 if (seq < 0 || res < 0)
639 if ((seq < av.getAlignment().getHeight())
640 && (res < av.getAlignment().getSequenceAt(seq).getLength()))
657 public void mouseOverSequence(SequenceI sequence, int index, int pos)
659 String tmp = sequence.hashCode() + " " + index + " " + pos;
661 if (lastMessage == null || !lastMessage.equals(tmp))
663 // System.err.println("mouseOver Sequence: "+tmp);
664 ssm.mouseOverSequence(sequence, index, pos, av);
670 * Highlight the mapped region described by the search results object (unless
671 * unchanged). This supports highlight of protein while mousing over linked
672 * cDNA and vice versa. The status bar is also updated to show the location of
673 * the start of the highlighted region.
676 public void highlightSequence(SearchResultsI results)
678 if (results == null || results.equals(lastSearchResults))
682 lastSearchResults = results;
684 if (av.isFollowHighlight())
686 // don't allow highlight of protein/cDNA to also scroll a complementary
687 // panel,as this sets up a feedback loop (scrolling panel 1 causes moused
688 // over residue to change abruptly, causing highlighted residue in panel 2
689 // to change, causing a scroll in panel 1 etc)
690 ap.setToScrollComplementPanel(false);
691 if (ap.scrollToPosition(results, false))
693 seqCanvas.revalidate();
695 ap.setToScrollComplementPanel(true);
697 if (seqCanvas.highlightSearchResults(results))
699 setStatusMessage(results);
704 public VamsasSource getVamsasSource()
706 return this.ap == null ? null : this.ap.av;
710 public void updateColours(SequenceI seq, int index)
712 System.out.println("update the seqPanel colours");
723 public void mouseMoved(MouseEvent evt)
727 // This is because MacOSX creates a mouseMoved
728 // If control is down, other platforms will not.
732 final int column = findColumn(evt);
733 int seq = findSeq(evt);
734 if (column < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
739 if (column == lastMouseColumn && seq == lastMouseSeq)
742 * just a pixel move without change of residue
746 lastMouseColumn = column;
749 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
751 if (column >= sequence.getLength())
757 * set status bar message, returning residue position in sequence
759 boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
760 final int pos = setStatusMessage(sequence, column, seq);
761 if (ssm != null && !isGapped)
763 mouseOverSequence(sequence, column, pos);
766 tooltipText.setLength(6); // Cuts the buffer back to <html>
768 SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
771 for (int g = 0; g < groups.length; g++)
773 if (groups[g].getStartRes() <= column
774 && groups[g].getEndRes() >= column)
776 if (!groups[g].getName().startsWith("JTreeGroup")
777 && !groups[g].getName().startsWith("JGroup"))
779 tooltipText.append(groups[g].getName());
782 if (groups[g].getDescription() != null)
784 tooltipText.append(": " + groups[g].getDescription());
791 * add any features at the position to the tooltip; if over a gap, only
792 * add features that straddle the gap (pos may be the residue before or
795 if (av.isShowSequenceFeatures())
797 List<SequenceFeature> features = ap.getFeatureRenderer()
798 .findFeaturesAtColumn(sequence, column + 1);
799 seqARep.appendFeatures(tooltipText, pos, features,
800 this.ap.getSeqPanel().seqCanvas.fr.getMinMax());
802 if (tooltipText.length() == 6) // <html>
804 setToolTipText(null);
809 String textString = tooltipText.toString();
810 if (lastTooltip == null || !lastTooltip.equals(textString))
812 String formattedTooltipText = JvSwingUtils.wrapTooltip(true,
814 setToolTipText(formattedTooltipText);
815 lastTooltip = textString;
820 private Point lastp = null;
825 * @see javax.swing.JComponent#getToolTipLocation(java.awt.event.MouseEvent)
828 public Point getToolTipLocation(MouseEvent event)
830 int x = event.getX(), w = getWidth();
831 int wdth = (w - x < 200) ? -(w / 2) : 5; // switch sides when tooltip is too
834 if (!event.isShiftDown() || p == null)
836 p = (tooltipText != null && tooltipText.length() > 6) ? new Point(
837 event.getX() + wdth, event.getY() - 20) : null;
840 * TODO: try to modify position region is not obcured by tooltip
848 * set when the current UI interaction has resulted in a change that requires
849 * overview shading to be recalculated. this could be changed to something
850 * more expressive that indicates what actually has changed, so selective
851 * redraws can be applied
853 private boolean needOverviewUpdate = false; // TODO: refactor to avcontroller
856 * set if av.getSelectionGroup() refers to a group that is defined on the
857 * alignment view, rather than a transient selection
859 // private boolean editingDefinedGroup = false; // TODO: refactor to
860 // avcontroller or viewModel
863 * Sets the status message in alignment panel, showing the sequence number
864 * (index) and id, and residue and residue position if not at a gap, for the
865 * given sequence and column position. Returns the residue position returned
866 * by Sequence.findPosition. Note this may be for the nearest adjacent residue
867 * if at a gapped position.
870 * aligned sequence object
874 * index of sequence in alignment
875 * @return sequence position of residue at column, or adjacent residue if at a
878 int setStatusMessage(SequenceI sequence, final int column, int seqIndex)
880 char sequenceChar = sequence.getCharAt(column);
881 int pos = sequence.findPosition(column);
882 setStatusMessage(sequence, seqIndex, sequenceChar, pos);
888 * Builds the status message for the current cursor location and writes it to
889 * the status bar, for example
892 * Sequence 3 ID: FER1_SOLLC
893 * Sequence 5 ID: FER1_PEA Residue: THR (4)
894 * Sequence 5 ID: FER1_PEA Residue: B (3)
895 * Sequence 6 ID: O.niloticus.3 Nucleotide: Uracil (2)
900 * sequence position in the alignment (1..)
901 * @param sequenceChar
902 * the character under the cursor
904 * the sequence residue position (if not over a gap)
906 protected void setStatusMessage(SequenceI sequence, int seqIndex,
907 char sequenceChar, int residuePos)
909 StringBuilder text = new StringBuilder(32);
912 * Sequence number (if known), and sequence name.
914 String seqno = seqIndex == -1 ? "" : " " + (seqIndex + 1);
915 text.append("Sequence").append(seqno).append(" ID: ")
916 .append(sequence.getName());
918 String residue = null;
921 * Try to translate the display character to residue name (null for gap).
923 boolean isGapped = Comparison.isGap(sequenceChar);
927 boolean nucleotide = av.getAlignment().isNucleotide();
928 String displayChar = String.valueOf(sequenceChar);
931 residue = ResidueProperties.nucleotideName.get(displayChar);
935 residue = "X".equalsIgnoreCase(displayChar) ? "X" : ("*"
936 .equals(displayChar) ? "STOP"
937 : ResidueProperties.aa2Triplet.get(displayChar));
939 text.append(" ").append(nucleotide ? "Nucleotide" : "Residue")
940 .append(": ").append(residue == null ? displayChar : residue);
942 text.append(" (").append(Integer.toString(residuePos)).append(")");
944 ap.alignFrame.statusBar.setText(text.toString());
948 * Set the status bar message to highlight the first matched position in
953 private void setStatusMessage(SearchResultsI results)
955 AlignmentI al = this.av.getAlignment();
956 int sequenceIndex = al.findIndex(results);
957 if (sequenceIndex == -1)
961 SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
962 for (SearchResultMatchI m : results.getResults())
964 SequenceI seq = m.getSequence();
965 if (seq.getDatasetSequence() != null)
967 seq = seq.getDatasetSequence();
972 int start = m.getStart();
973 setStatusMessage(seq, sequenceIndex, seq.getCharAt(start - 1),
984 public void mouseDragged(MouseEvent evt)
986 if (mouseWheelPressed)
988 boolean inSplitFrame = ap.av.getCodingComplement() != null;
989 boolean copyChanges = inSplitFrame && av.isProteinFontAsCdna();
991 int oldWidth = av.getCharWidth();
993 // Which is bigger, left-right or up-down?
994 if (Math.abs(evt.getY() - lastMousePress.getY()) > Math.abs(evt
995 .getX() - lastMousePress.getX()))
998 * on drag up or down, decrement or increment font size
1000 int fontSize = av.font.getSize();
1001 boolean fontChanged = false;
1003 if (evt.getY() < lastMousePress.getY())
1008 else if (evt.getY() > lastMousePress.getY())
1021 Font newFont = new Font(av.font.getName(), av.font.getStyle(),
1023 av.setFont(newFont, true);
1024 av.setCharWidth(oldWidth);
1028 ap.av.getCodingComplement().setFont(newFont, true);
1029 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1030 .getSplitViewContainer();
1031 splitFrame.adjustLayout();
1032 splitFrame.repaint();
1039 * on drag left or right, decrement or increment character width
1042 if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
1044 newWidth = av.getCharWidth() - 1;
1045 av.setCharWidth(newWidth);
1047 else if (evt.getX() > lastMousePress.getX())
1049 newWidth = av.getCharWidth() + 1;
1050 av.setCharWidth(newWidth);
1054 ap.paintAlignment(false);
1058 * need to ensure newWidth is set on cdna, regardless of which
1059 * panel the mouse drag happened in; protein will compute its
1060 * character width as 1:1 or 3:1
1062 av.getCodingComplement().setCharWidth(newWidth);
1063 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1064 .getSplitViewContainer();
1065 splitFrame.adjustLayout();
1066 splitFrame.repaint();
1071 FontMetrics fm = getFontMetrics(av.getFont());
1072 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1074 lastMousePress = evt.getPoint();
1081 doMouseDraggedDefineMode(evt);
1085 int res = findColumn(evt);
1092 if ((lastres == -1) || (lastres == res))
1097 if ((res < av.getAlignment().getWidth()) && (res < lastres))
1099 // dragLeft, delete gap
1100 editSequence(false, false, res);
1104 editSequence(true, false, res);
1107 mouseDragging = true;
1108 if (scrollThread != null)
1110 scrollThread.setEvent(evt);
1114 // TODO: Make it more clever than many booleans
1115 synchronized void editSequence(boolean insertGap, boolean editSeq,
1119 int fixedRight = -1;
1120 boolean fixedColumns = false;
1121 SequenceGroup sg = av.getSelectionGroup();
1123 SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1125 // No group, but the sequence may represent a group
1126 if (!groupEditing && av.hasHiddenRows())
1128 if (av.isHiddenRepSequence(seq))
1130 sg = av.getRepresentedSequences(seq);
1131 groupEditing = true;
1135 StringBuilder message = new StringBuilder(64);
1138 message.append("Edit group:");
1139 if (editCommand == null)
1141 editCommand = new EditCommand(
1142 MessageManager.getString("action.edit_group"));
1147 message.append("Edit sequence: " + seq.getName());
1148 String label = seq.getName();
1149 if (label.length() > 10)
1151 label = label.substring(0, 10);
1153 if (editCommand == null)
1155 editCommand = new EditCommand(MessageManager.formatMessage(
1156 "label.edit_params", new String[] { label }));
1162 message.append(" insert ");
1166 message.append(" delete ");
1169 message.append(Math.abs(startres - lastres) + " gaps.");
1170 ap.alignFrame.statusBar.setText(message.toString());
1172 // Are we editing within a selection group?
1174 || (sg != null && sg.getSequences(av.getHiddenRepSequences())
1177 fixedColumns = true;
1179 // sg might be null as the user may only see 1 sequence,
1180 // but the sequence represents a group
1183 if (!av.isHiddenRepSequence(seq))
1188 sg = av.getRepresentedSequences(seq);
1191 fixedLeft = sg.getStartRes();
1192 fixedRight = sg.getEndRes();
1194 if ((startres < fixedLeft && lastres >= fixedLeft)
1195 || (startres >= fixedLeft && lastres < fixedLeft)
1196 || (startres > fixedRight && lastres <= fixedRight)
1197 || (startres <= fixedRight && lastres > fixedRight))
1203 if (fixedLeft > startres)
1205 fixedRight = fixedLeft - 1;
1208 else if (fixedRight < startres)
1210 fixedLeft = fixedRight;
1215 if (av.hasHiddenColumns())
1217 fixedColumns = true;
1218 int y1 = av.getAlignment().getHiddenColumns()
1219 .getHiddenBoundaryLeft(startres);
1220 int y2 = av.getAlignment().getHiddenColumns()
1221 .getHiddenBoundaryRight(startres);
1223 if ((insertGap && startres > y1 && lastres < y1)
1224 || (!insertGap && startres < y2 && lastres > y2))
1230 // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1231 // Selection spans a hidden region
1232 if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1240 fixedRight = y2 - 1;
1247 List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1248 int g, groupSize = vseqs.size();
1249 SequenceI[] groupSeqs = new SequenceI[groupSize];
1250 for (g = 0; g < groupSeqs.length; g++)
1252 groupSeqs[g] = vseqs.get(g);
1258 // If the user has selected the whole sequence, and is dragging to
1259 // the right, we can still extend the alignment and selectionGroup
1260 if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1261 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1263 sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1264 fixedRight = sg.getEndRes();
1267 // Is it valid with fixed columns??
1268 // Find the next gap before the end
1269 // of the visible region boundary
1270 boolean blank = false;
1271 for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1275 for (g = 0; g < groupSize; g++)
1277 for (int j = 0; j < startres - lastres; j++)
1279 if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1294 if (sg.getSize() == av.getAlignment().getHeight())
1296 if ((av.hasHiddenColumns() && startres < av.getAlignment()
1297 .getHiddenColumns().getHiddenBoundaryRight(startres)))
1303 int alWidth = av.getAlignment().getWidth();
1304 if (av.hasHiddenRows())
1306 int hwidth = av.getAlignment().getHiddenSequences()
1308 if (hwidth > alWidth)
1313 // We can still insert gaps if the selectionGroup
1314 // contains all the sequences
1315 sg.setEndRes(sg.getEndRes() + startres - lastres);
1316 fixedRight = alWidth + startres - lastres;
1327 else if (!insertGap)
1329 // / Are we able to delete?
1330 // ie are all columns blank?
1332 for (g = 0; g < groupSize; g++)
1334 for (int j = startres; j < lastres; j++)
1336 if (groupSeqs[g].getLength() <= j)
1341 if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1343 // Not a gap, block edit not valid
1353 // dragging to the right
1354 if (fixedColumns && fixedRight != -1)
1356 for (int j = lastres; j < startres; j++)
1358 insertChar(j, groupSeqs, fixedRight);
1363 appendEdit(Action.INSERT_GAP, groupSeqs, startres, startres
1369 // dragging to the left
1370 if (fixedColumns && fixedRight != -1)
1372 for (int j = lastres; j > startres; j--)
1374 deleteChar(startres, groupSeqs, fixedRight);
1379 appendEdit(Action.DELETE_GAP, groupSeqs, startres, lastres
1386 // ///Editing a single sequence///////////
1390 // dragging to the right
1391 if (fixedColumns && fixedRight != -1)
1393 for (int j = lastres; j < startres; j++)
1395 insertChar(j, new SequenceI[] { seq }, fixedRight);
1400 appendEdit(Action.INSERT_GAP, new SequenceI[] { seq }, lastres,
1401 startres - lastres);
1408 // dragging to the left
1409 if (fixedColumns && fixedRight != -1)
1411 for (int j = lastres; j > startres; j--)
1413 if (!Comparison.isGap(seq.getCharAt(startres)))
1418 deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1423 // could be a keyboard edit trying to delete none gaps
1425 for (int m = startres; m < lastres; m++)
1427 if (!Comparison.isGap(seq.getCharAt(m)))
1436 appendEdit(Action.DELETE_GAP, new SequenceI[] { seq },
1442 {// insertGap==false AND editSeq==TRUE;
1443 if (fixedColumns && fixedRight != -1)
1445 for (int j = lastres; j < startres; j++)
1447 insertChar(j, new SequenceI[] { seq }, fixedRight);
1452 appendEdit(Action.INSERT_NUC, new SequenceI[] { seq }, lastres,
1453 startres - lastres);
1460 seqCanvas.repaint();
1463 void insertChar(int j, SequenceI[] seq, int fixedColumn)
1465 int blankColumn = fixedColumn;
1466 for (int s = 0; s < seq.length; s++)
1468 // Find the next gap before the end of the visible region boundary
1469 // If lastCol > j, theres a boundary after the gap insertion
1471 for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1473 if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1475 // Theres a space, so break and insert the gap
1480 if (blankColumn <= j)
1482 blankColumn = fixedColumn;
1488 appendEdit(Action.DELETE_GAP, seq, blankColumn, 1);
1490 appendEdit(Action.INSERT_GAP, seq, j, 1);
1495 * Helper method to add and perform one edit action.
1502 protected void appendEdit(Action action, SequenceI[] seq, int pos,
1506 final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1507 av.getAlignment().getGapCharacter());
1509 editCommand.appendEdit(edit, av.getAlignment(), true, null);
1512 void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1515 appendEdit(Action.DELETE_GAP, seq, j, 1);
1517 appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1);
1527 public void mouseEntered(MouseEvent e)
1534 if (scrollThread != null)
1536 scrollThread.running = false;
1537 scrollThread = null;
1548 public void mouseExited(MouseEvent e)
1550 if (av.getWrapAlignment())
1557 scrollThread = new ScrollThread();
1562 * Handler for double-click on a position with one or more sequence features.
1563 * Opens the Amend Features dialog to allow feature details to be amended, or
1564 * the feature deleted.
1567 public void mouseClicked(MouseEvent evt)
1569 SequenceGroup sg = null;
1570 SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
1571 if (evt.getClickCount() > 1)
1573 sg = av.getSelectionGroup();
1574 if (sg != null && sg.getSize() == 1
1575 && sg.getEndRes() - sg.getStartRes() < 2)
1577 av.setSelectionGroup(null);
1580 int column = findColumn(evt);
1583 * find features at the position (if not gapped), or straddling
1584 * the position (if at a gap)
1586 List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1587 .findFeaturesAtColumn(sequence, column + 1);
1589 if (!features.isEmpty())
1592 * highlight the first feature at the position on the alignment
1594 SearchResultsI highlight = new SearchResults();
1595 highlight.addResult(sequence, features.get(0).getBegin(), features
1597 seqCanvas.highlightSearchResults(highlight);
1600 * open the Amend Features dialog; clear highlighting afterwards,
1601 * whether changes were made or not
1603 List<SequenceI> seqs = Collections.singletonList(sequence);
1604 seqCanvas.getFeatureRenderer().amendFeatures(seqs, features, false,
1606 seqCanvas.highlightSearchResults(null);
1612 public void mouseWheelMoved(MouseWheelEvent e)
1615 if (e.getWheelRotation() > 0)
1617 if (e.isShiftDown())
1619 av.getRanges().scrollRight(true);
1624 av.getRanges().scrollUp(false);
1629 if (e.isShiftDown())
1631 av.getRanges().scrollRight(false);
1635 av.getRanges().scrollUp(true);
1638 // TODO Update tooltip for new position.
1647 public void doMousePressedDefineMode(MouseEvent evt)
1649 final int res = findColumn(evt);
1650 final int seq = findSeq(evt);
1652 needOverviewUpdate = false;
1654 startWrapBlock = wrappedBlock;
1656 if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1658 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
1659 .getString("label.cannot_edit_annotations_in_wrapped_view"),
1660 MessageManager.getString("label.wrapped_view_no_edit"),
1661 JvOptionPane.WARNING_MESSAGE);
1665 if (seq < 0 || res < 0)
1670 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1672 if ((sequence == null) || (res > sequence.getLength()))
1677 stretchGroup = av.getSelectionGroup();
1679 if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1681 stretchGroup = av.getAlignment().findGroup(sequence, res);
1682 if (stretchGroup != null)
1684 // only update the current selection if the popup menu has a group to
1686 av.setSelectionGroup(stretchGroup);
1690 if (evt.isPopupTrigger()) // Mac: mousePressed
1697 * defer right-mouse click handling to mouseReleased on Windows
1698 * (where isPopupTrigger() will answer true)
1699 * NB isRightMouseButton is also true for Cmd-click on Mac
1701 if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1708 seqCanvas.cursorX = findColumn(evt);
1709 seqCanvas.cursorY = findSeq(evt);
1710 seqCanvas.repaint();
1714 if (stretchGroup == null)
1716 // Only if left mouse button do we want to change group sizes
1718 // define a new group here
1719 SequenceGroup sg = new SequenceGroup();
1720 sg.setStartRes(res);
1722 sg.addSequence(sequence, false);
1723 av.setSelectionGroup(sg);
1726 if (av.getConservationSelected())
1728 SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1732 if (av.getAbovePIDThreshold())
1734 SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1737 // TODO: stretchGroup will always be not null. Is this a merge error ?
1738 if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1740 // Edit end res position of selected group
1741 changeEndRes = true;
1743 else if ((stretchGroup != null)
1744 && (stretchGroup.getStartRes() == res))
1746 // Edit end res position of selected group
1747 changeStartRes = true;
1749 stretchGroup.getWidth();
1752 seqCanvas.repaint();
1756 * Build and show a pop-up menu at the right-click mouse position
1762 void showPopupMenu(MouseEvent evt)
1764 final int column = findColumn(evt);
1765 final int seq = findSeq(evt);
1766 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1767 List<SequenceFeature> allFeatures = ap.getFeatureRenderer()
1768 .findFeaturesAtColumn(sequence, column + 1);
1769 List<String> links = new ArrayList<>();
1770 for (SequenceFeature sf : allFeatures)
1772 if (sf.links != null)
1774 for (String link : sf.links)
1781 PopupMenu pop = new PopupMenu(ap, null, links);
1782 pop.show(this, evt.getX(), evt.getY());
1786 * Update the display after mouse up on a selection or group
1789 * mouse released event details
1791 * true if this event is happening after a mouse drag (rather than a
1794 public void doMouseReleasedDefineMode(MouseEvent evt, boolean afterDrag)
1796 if (stretchGroup == null)
1800 // always do this - annotation has own state
1801 // but defer colourscheme update until hidden sequences are passed in
1802 boolean vischange = stretchGroup.recalcConservation(true);
1803 needOverviewUpdate |= vischange && av.isSelectionDefinedGroup()
1805 if (stretchGroup.cs != null)
1807 stretchGroup.cs.alignmentChanged(stretchGroup,
1808 av.getHiddenRepSequences());
1810 ResidueShaderI groupColourScheme = stretchGroup.getGroupColourScheme();
1811 String name = stretchGroup.getName();
1812 if (stretchGroup.cs.conservationApplied())
1814 SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1816 if (stretchGroup.cs.getThreshold() > 0)
1818 SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1821 PaintRefresher.Refresh(this, av.getSequenceSetId());
1822 ap.paintAlignment(needOverviewUpdate);
1823 needOverviewUpdate = false;
1824 changeEndRes = false;
1825 changeStartRes = false;
1826 stretchGroup = null;
1836 public void doMouseDraggedDefineMode(MouseEvent evt)
1838 int res = findColumn(evt);
1839 int y = findSeq(evt);
1841 if (wrappedBlock != startWrapBlock)
1846 if (stretchGroup == null)
1851 if (res >= av.getAlignment().getWidth())
1853 res = av.getAlignment().getWidth() - 1;
1856 if (stretchGroup.getEndRes() == res)
1858 // Edit end res position of selected group
1859 changeEndRes = true;
1861 else if (stretchGroup.getStartRes() == res)
1863 // Edit start res position of selected group
1864 changeStartRes = true;
1867 if (res < av.getRanges().getStartRes())
1869 res = av.getRanges().getStartRes();
1874 if (res > (stretchGroup.getStartRes() - 1))
1876 stretchGroup.setEndRes(res);
1877 needOverviewUpdate |= av.isSelectionDefinedGroup();
1880 else if (changeStartRes)
1882 if (res < (stretchGroup.getEndRes() + 1))
1884 stretchGroup.setStartRes(res);
1885 needOverviewUpdate |= av.isSelectionDefinedGroup();
1889 int dragDirection = 0;
1895 else if (y < oldSeq)
1900 while ((y != oldSeq) && (oldSeq > -1)
1901 && (y < av.getAlignment().getHeight()))
1903 // This routine ensures we don't skip any sequences, as the
1904 // selection is quite slow.
1905 Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1907 oldSeq += dragDirection;
1914 Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1916 if (stretchGroup.getSequences(null).contains(nextSeq))
1918 stretchGroup.deleteSequence(seq, false);
1919 needOverviewUpdate |= av.isSelectionDefinedGroup();
1925 stretchGroup.addSequence(seq, false);
1928 stretchGroup.addSequence(nextSeq, false);
1929 needOverviewUpdate |= av.isSelectionDefinedGroup();
1938 mouseDragging = true;
1940 if (scrollThread != null)
1942 scrollThread.setEvent(evt);
1945 seqCanvas.repaint();
1948 void scrollCanvas(MouseEvent evt)
1952 if (scrollThread != null)
1954 scrollThread.running = false;
1955 scrollThread = null;
1957 mouseDragging = false;
1961 if (scrollThread == null)
1963 scrollThread = new ScrollThread();
1966 mouseDragging = true;
1967 scrollThread.setEvent(evt);
1972 // this class allows scrolling off the bottom of the visible alignment
1973 class ScrollThread extends Thread
1977 boolean running = false;
1979 public ScrollThread()
1984 public void setEvent(MouseEvent e)
1989 public void stopScrolling()
2003 if (mouseDragging && (evt.getY() < 0)
2004 && (av.getRanges().getStartSeq() > 0))
2006 running = av.getRanges().scrollUp(true);
2009 if (mouseDragging && (evt.getY() >= getHeight())
2010 && (av.getAlignment().getHeight() > av.getRanges()
2013 running = av.getRanges().scrollUp(false);
2016 if (mouseDragging && (evt.getX() < 0))
2018 running = av.getRanges().scrollRight(false);
2020 else if (mouseDragging && (evt.getX() >= getWidth()))
2022 running = av.getRanges().scrollRight(true);
2029 } catch (Exception ex)
2037 * modify current selection according to a received message.
2040 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
2041 HiddenColumns hidden, SelectionSource source)
2043 // TODO: fix this hack - source of messages is align viewport, but SeqPanel
2044 // handles selection messages...
2045 // TODO: extend config options to allow user to control if selections may be
2046 // shared between viewports.
2047 boolean iSentTheSelection = (av == source || (source instanceof AlignViewport && ((AlignmentViewport) source)
2048 .getSequenceSetId().equals(av.getSequenceSetId())));
2050 if (iSentTheSelection)
2052 // respond to our own event by updating dependent dialogs
2053 if (ap.getCalculationDialog() != null)
2055 ap.getCalculationDialog().validateCalcTypes();
2061 // process further ?
2062 if (!av.followSelection)
2068 * Ignore the selection if there is one of our own pending.
2070 if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
2076 * Check for selection in a view of which this one is a dna/protein
2079 if (selectionFromTranslation(seqsel, colsel, hidden, source))
2084 // do we want to thread this ? (contention with seqsel and colsel locks, I
2087 * only copy colsel if there is a real intersection between
2088 * sequence selection and this panel's alignment
2090 boolean repaint = false;
2091 boolean copycolsel = false;
2093 SequenceGroup sgroup = null;
2094 if (seqsel != null && seqsel.getSize() > 0)
2096 if (av.getAlignment() == null)
2098 Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2099 + " ViewId=" + av.getViewId()
2100 + " 's alignment is NULL! returning immediately.");
2103 sgroup = seqsel.intersect(av.getAlignment(),
2104 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2105 if ((sgroup != null && sgroup.getSize() > 0))
2110 if (sgroup != null && sgroup.getSize() > 0)
2112 av.setSelectionGroup(sgroup);
2116 av.setSelectionGroup(null);
2118 av.isSelectionGroupChanged(true);
2123 // the current selection is unset or from a previous message
2124 // so import the new colsel.
2125 if (colsel == null || colsel.isEmpty())
2127 if (av.getColumnSelection() != null)
2129 av.getColumnSelection().clear();
2135 // TODO: shift colSel according to the intersecting sequences
2136 if (av.getColumnSelection() == null)
2138 av.setColumnSelection(new ColumnSelection(colsel));
2142 av.getColumnSelection().setElementsFrom(colsel,
2143 av.getAlignment().getHiddenColumns());
2146 av.isColSelChanged(true);
2151 && av.hasHiddenColumns()
2152 && (av.getAlignment().getHiddenColumns() == null || av
2153 .getAlignment().getHiddenColumns().getHiddenRegions() == null))
2155 System.err.println("Bad things");
2157 if (repaint) // always true!
2159 // probably finessing with multiple redraws here
2160 PaintRefresher.Refresh(this, av.getSequenceSetId());
2161 // ap.paintAlignment(false);
2164 // lastly, update dependent dialogs
2165 if (ap.getCalculationDialog() != null)
2167 ap.getCalculationDialog().validateCalcTypes();
2173 * If this panel is a cdna/protein translation view of the selection source,
2174 * tries to map the source selection to a local one, and returns true. Else
2181 protected boolean selectionFromTranslation(SequenceGroup seqsel,
2182 ColumnSelection colsel, HiddenColumns hidden,
2183 SelectionSource source)
2185 if (!(source instanceof AlignViewportI))
2189 final AlignViewportI sourceAv = (AlignViewportI) source;
2190 if (sourceAv.getCodingComplement() != av
2191 && av.getCodingComplement() != sourceAv)
2197 * Map sequence selection
2199 SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2200 av.setSelectionGroup(sg);
2201 av.isSelectionGroupChanged(true);
2204 * Map column selection
2206 // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2208 ColumnSelection cs = new ColumnSelection();
2209 HiddenColumns hs = new HiddenColumns();
2210 MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2211 av.setColumnSelection(cs);
2212 av.getAlignment().setHiddenColumns(hs);
2214 // lastly, update any dependent dialogs
2215 if (ap.getCalculationDialog() != null)
2217 ap.getCalculationDialog().validateCalcTypes();
2220 PaintRefresher.Refresh(this, av.getSequenceSetId());