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 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 setStatusMessage(results);
698 seqCanvas.highlightSearchResults(results);
702 public VamsasSource getVamsasSource()
704 return this.ap == null ? null : this.ap.av;
708 public void updateColours(SequenceI seq, int index)
710 System.out.println("update the seqPanel colours");
721 public void mouseMoved(MouseEvent evt)
725 // This is because MacOSX creates a mouseMoved
726 // If control is down, other platforms will not.
730 final int column = findColumn(evt);
731 int seq = findSeq(evt);
732 if (column < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
737 if (column == lastMouseColumn && seq == lastMouseSeq)
740 * just a pixel move without change of residue
744 lastMouseColumn = column;
747 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
749 if (column >= sequence.getLength())
755 * set status bar message, returning residue position in sequence
757 boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
758 final int pos = setStatusMessage(sequence, column, seq);
759 if (ssm != null && !isGapped)
761 mouseOverSequence(sequence, column, pos);
764 tooltipText.setLength(6); // Cuts the buffer back to <html>
766 SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
769 for (int g = 0; g < groups.length; g++)
771 if (groups[g].getStartRes() <= column
772 && groups[g].getEndRes() >= column)
774 if (!groups[g].getName().startsWith("JTreeGroup")
775 && !groups[g].getName().startsWith("JGroup"))
777 tooltipText.append(groups[g].getName());
780 if (groups[g].getDescription() != null)
782 tooltipText.append(": " + groups[g].getDescription());
789 * add any features at the position to the tooltip; if over a gap, only
790 * add features that straddle the gap (pos may be the residue before or
793 if (av.isShowSequenceFeatures())
795 List<SequenceFeature> features = ap.getFeatureRenderer()
796 .findFeaturesAtColumn(sequence, column + 1);
797 seqARep.appendFeatures(tooltipText, pos, features,
798 this.ap.getSeqPanel().seqCanvas.fr.getMinMax());
800 if (tooltipText.length() == 6) // <html>
802 setToolTipText(null);
807 String textString = tooltipText.toString();
808 if (lastTooltip == null || !lastTooltip.equals(textString))
810 String formattedTooltipText = JvSwingUtils.wrapTooltip(true,
812 setToolTipText(formattedTooltipText);
813 lastTooltip = textString;
818 private Point lastp = null;
823 * @see javax.swing.JComponent#getToolTipLocation(java.awt.event.MouseEvent)
826 public Point getToolTipLocation(MouseEvent event)
828 int x = event.getX(), w = getWidth();
829 int wdth = (w - x < 200) ? -(w / 2) : 5; // switch sides when tooltip is too
832 if (!event.isShiftDown() || p == null)
834 p = (tooltipText != null && tooltipText.length() > 6) ? new Point(
835 event.getX() + wdth, event.getY() - 20) : null;
838 * TODO: try to modify position region is not obcured by tooltip
846 * set when the current UI interaction has resulted in a change that requires
847 * overview shading to be recalculated. this could be changed to something
848 * more expressive that indicates what actually has changed, so selective
849 * redraws can be applied
851 private boolean needOverviewUpdate = false; // TODO: refactor to avcontroller
854 * set if av.getSelectionGroup() refers to a group that is defined on the
855 * alignment view, rather than a transient selection
857 // private boolean editingDefinedGroup = false; // TODO: refactor to
858 // avcontroller or viewModel
861 * Sets the status message in alignment panel, showing the sequence number
862 * (index) and id, and residue and residue position if not at a gap, for the
863 * given sequence and column position. Returns the residue position returned
864 * by Sequence.findPosition. Note this may be for the nearest adjacent residue
865 * if at a gapped position.
868 * aligned sequence object
872 * index of sequence in alignment
873 * @return sequence position of residue at column, or adjacent residue if at a
876 int setStatusMessage(SequenceI sequence, final int column, int seqIndex)
878 char sequenceChar = sequence.getCharAt(column);
879 int pos = sequence.findPosition(column);
880 setStatusMessage(sequence, seqIndex, sequenceChar, pos);
886 * Builds the status message for the current cursor location and writes it to
887 * the status bar, for example
890 * Sequence 3 ID: FER1_SOLLC
891 * Sequence 5 ID: FER1_PEA Residue: THR (4)
892 * Sequence 5 ID: FER1_PEA Residue: B (3)
893 * Sequence 6 ID: O.niloticus.3 Nucleotide: Uracil (2)
898 * sequence position in the alignment (1..)
899 * @param sequenceChar
900 * the character under the cursor
902 * the sequence residue position (if not over a gap)
904 protected void setStatusMessage(SequenceI sequence, int seqIndex,
905 char sequenceChar, int residuePos)
907 StringBuilder text = new StringBuilder(32);
910 * Sequence number (if known), and sequence name.
912 String seqno = seqIndex == -1 ? "" : " " + (seqIndex + 1);
913 text.append("Sequence").append(seqno).append(" ID: ")
914 .append(sequence.getName());
916 String residue = null;
919 * Try to translate the display character to residue name (null for gap).
921 boolean isGapped = Comparison.isGap(sequenceChar);
925 boolean nucleotide = av.getAlignment().isNucleotide();
926 String displayChar = String.valueOf(sequenceChar);
929 residue = ResidueProperties.nucleotideName.get(displayChar);
933 residue = "X".equalsIgnoreCase(displayChar) ? "X" : ("*"
934 .equals(displayChar) ? "STOP"
935 : ResidueProperties.aa2Triplet.get(displayChar));
937 text.append(" ").append(nucleotide ? "Nucleotide" : "Residue")
938 .append(": ").append(residue == null ? displayChar : residue);
940 text.append(" (").append(Integer.toString(residuePos)).append(")");
942 ap.alignFrame.statusBar.setText(text.toString());
946 * Set the status bar message to highlight the first matched position in
951 private void setStatusMessage(SearchResultsI results)
953 AlignmentI al = this.av.getAlignment();
954 int sequenceIndex = al.findIndex(results);
955 if (sequenceIndex == -1)
959 SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
960 for (SearchResultMatchI m : results.getResults())
962 SequenceI seq = m.getSequence();
963 if (seq.getDatasetSequence() != null)
965 seq = seq.getDatasetSequence();
970 int start = m.getStart();
971 setStatusMessage(seq, sequenceIndex, seq.getCharAt(start - 1),
982 public void mouseDragged(MouseEvent evt)
984 if (mouseWheelPressed)
986 boolean inSplitFrame = ap.av.getCodingComplement() != null;
987 boolean copyChanges = inSplitFrame && av.isProteinFontAsCdna();
989 int oldWidth = av.getCharWidth();
991 // Which is bigger, left-right or up-down?
992 if (Math.abs(evt.getY() - lastMousePress.getY()) > Math.abs(evt
993 .getX() - lastMousePress.getX()))
996 * on drag up or down, decrement or increment font size
998 int fontSize = av.font.getSize();
999 boolean fontChanged = false;
1001 if (evt.getY() < lastMousePress.getY())
1006 else if (evt.getY() > lastMousePress.getY())
1019 Font newFont = new Font(av.font.getName(), av.font.getStyle(),
1021 av.setFont(newFont, true);
1022 av.setCharWidth(oldWidth);
1026 ap.av.getCodingComplement().setFont(newFont, true);
1027 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1028 .getSplitViewContainer();
1029 splitFrame.adjustLayout();
1030 splitFrame.repaint();
1037 * on drag left or right, decrement or increment character width
1040 if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
1042 newWidth = av.getCharWidth() - 1;
1043 av.setCharWidth(newWidth);
1045 else if (evt.getX() > lastMousePress.getX())
1047 newWidth = av.getCharWidth() + 1;
1048 av.setCharWidth(newWidth);
1052 ap.paintAlignment(false);
1056 * need to ensure newWidth is set on cdna, regardless of which
1057 * panel the mouse drag happened in; protein will compute its
1058 * character width as 1:1 or 3:1
1060 av.getCodingComplement().setCharWidth(newWidth);
1061 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1062 .getSplitViewContainer();
1063 splitFrame.adjustLayout();
1064 splitFrame.repaint();
1069 FontMetrics fm = getFontMetrics(av.getFont());
1070 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1072 lastMousePress = evt.getPoint();
1079 doMouseDraggedDefineMode(evt);
1083 int res = findColumn(evt);
1090 if ((lastres == -1) || (lastres == res))
1095 if ((res < av.getAlignment().getWidth()) && (res < lastres))
1097 // dragLeft, delete gap
1098 editSequence(false, false, res);
1102 editSequence(true, false, res);
1105 mouseDragging = true;
1106 if (scrollThread != null)
1108 scrollThread.setEvent(evt);
1112 // TODO: Make it more clever than many booleans
1113 synchronized void editSequence(boolean insertGap, boolean editSeq,
1117 int fixedRight = -1;
1118 boolean fixedColumns = false;
1119 SequenceGroup sg = av.getSelectionGroup();
1121 SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1123 // No group, but the sequence may represent a group
1124 if (!groupEditing && av.hasHiddenRows())
1126 if (av.isHiddenRepSequence(seq))
1128 sg = av.getRepresentedSequences(seq);
1129 groupEditing = true;
1133 StringBuilder message = new StringBuilder(64);
1136 message.append("Edit group:");
1137 if (editCommand == null)
1139 editCommand = new EditCommand(
1140 MessageManager.getString("action.edit_group"));
1145 message.append("Edit sequence: " + seq.getName());
1146 String label = seq.getName();
1147 if (label.length() > 10)
1149 label = label.substring(0, 10);
1151 if (editCommand == null)
1153 editCommand = new EditCommand(MessageManager.formatMessage(
1154 "label.edit_params", new String[] { label }));
1160 message.append(" insert ");
1164 message.append(" delete ");
1167 message.append(Math.abs(startres - lastres) + " gaps.");
1168 ap.alignFrame.statusBar.setText(message.toString());
1170 // Are we editing within a selection group?
1172 || (sg != null && sg.getSequences(av.getHiddenRepSequences())
1175 fixedColumns = true;
1177 // sg might be null as the user may only see 1 sequence,
1178 // but the sequence represents a group
1181 if (!av.isHiddenRepSequence(seq))
1186 sg = av.getRepresentedSequences(seq);
1189 fixedLeft = sg.getStartRes();
1190 fixedRight = sg.getEndRes();
1192 if ((startres < fixedLeft && lastres >= fixedLeft)
1193 || (startres >= fixedLeft && lastres < fixedLeft)
1194 || (startres > fixedRight && lastres <= fixedRight)
1195 || (startres <= fixedRight && lastres > fixedRight))
1201 if (fixedLeft > startres)
1203 fixedRight = fixedLeft - 1;
1206 else if (fixedRight < startres)
1208 fixedLeft = fixedRight;
1213 if (av.hasHiddenColumns())
1215 fixedColumns = true;
1216 int y1 = av.getAlignment().getHiddenColumns()
1217 .getHiddenBoundaryLeft(startres);
1218 int y2 = av.getAlignment().getHiddenColumns()
1219 .getHiddenBoundaryRight(startres);
1221 if ((insertGap && startres > y1 && lastres < y1)
1222 || (!insertGap && startres < y2 && lastres > y2))
1228 // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1229 // Selection spans a hidden region
1230 if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1238 fixedRight = y2 - 1;
1245 List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1246 int g, groupSize = vseqs.size();
1247 SequenceI[] groupSeqs = new SequenceI[groupSize];
1248 for (g = 0; g < groupSeqs.length; g++)
1250 groupSeqs[g] = vseqs.get(g);
1256 // If the user has selected the whole sequence, and is dragging to
1257 // the right, we can still extend the alignment and selectionGroup
1258 if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1259 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1261 sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1262 fixedRight = sg.getEndRes();
1265 // Is it valid with fixed columns??
1266 // Find the next gap before the end
1267 // of the visible region boundary
1268 boolean blank = false;
1269 for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1273 for (g = 0; g < groupSize; g++)
1275 for (int j = 0; j < startres - lastres; j++)
1277 if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1292 if (sg.getSize() == av.getAlignment().getHeight())
1294 if ((av.hasHiddenColumns() && startres < av.getAlignment()
1295 .getHiddenColumns().getHiddenBoundaryRight(startres)))
1301 int alWidth = av.getAlignment().getWidth();
1302 if (av.hasHiddenRows())
1304 int hwidth = av.getAlignment().getHiddenSequences()
1306 if (hwidth > alWidth)
1311 // We can still insert gaps if the selectionGroup
1312 // contains all the sequences
1313 sg.setEndRes(sg.getEndRes() + startres - lastres);
1314 fixedRight = alWidth + startres - lastres;
1325 else if (!insertGap)
1327 // / Are we able to delete?
1328 // ie are all columns blank?
1330 for (g = 0; g < groupSize; g++)
1332 for (int j = startres; j < lastres; j++)
1334 if (groupSeqs[g].getLength() <= j)
1339 if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1341 // Not a gap, block edit not valid
1351 // dragging to the right
1352 if (fixedColumns && fixedRight != -1)
1354 for (int j = lastres; j < startres; j++)
1356 insertChar(j, groupSeqs, fixedRight);
1361 appendEdit(Action.INSERT_GAP, groupSeqs, startres, startres
1367 // dragging to the left
1368 if (fixedColumns && fixedRight != -1)
1370 for (int j = lastres; j > startres; j--)
1372 deleteChar(startres, groupSeqs, fixedRight);
1377 appendEdit(Action.DELETE_GAP, groupSeqs, startres, lastres
1384 // ///Editing a single sequence///////////
1388 // dragging to the right
1389 if (fixedColumns && fixedRight != -1)
1391 for (int j = lastres; j < startres; j++)
1393 insertChar(j, new SequenceI[] { seq }, fixedRight);
1398 appendEdit(Action.INSERT_GAP, new SequenceI[] { seq }, lastres,
1399 startres - lastres);
1406 // dragging to the left
1407 if (fixedColumns && fixedRight != -1)
1409 for (int j = lastres; j > startres; j--)
1411 if (!Comparison.isGap(seq.getCharAt(startres)))
1416 deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1421 // could be a keyboard edit trying to delete none gaps
1423 for (int m = startres; m < lastres; m++)
1425 if (!Comparison.isGap(seq.getCharAt(m)))
1434 appendEdit(Action.DELETE_GAP, new SequenceI[] { seq },
1440 {// insertGap==false AND editSeq==TRUE;
1441 if (fixedColumns && fixedRight != -1)
1443 for (int j = lastres; j < startres; j++)
1445 insertChar(j, new SequenceI[] { seq }, fixedRight);
1450 appendEdit(Action.INSERT_NUC, new SequenceI[] { seq }, lastres,
1451 startres - lastres);
1458 seqCanvas.repaint();
1461 void insertChar(int j, SequenceI[] seq, int fixedColumn)
1463 int blankColumn = fixedColumn;
1464 for (int s = 0; s < seq.length; s++)
1466 // Find the next gap before the end of the visible region boundary
1467 // If lastCol > j, theres a boundary after the gap insertion
1469 for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1471 if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1473 // Theres a space, so break and insert the gap
1478 if (blankColumn <= j)
1480 blankColumn = fixedColumn;
1486 appendEdit(Action.DELETE_GAP, seq, blankColumn, 1);
1488 appendEdit(Action.INSERT_GAP, seq, j, 1);
1493 * Helper method to add and perform one edit action.
1500 protected void appendEdit(Action action, SequenceI[] seq, int pos,
1504 final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1505 av.getAlignment().getGapCharacter());
1507 editCommand.appendEdit(edit, av.getAlignment(), true, null);
1510 void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1513 appendEdit(Action.DELETE_GAP, seq, j, 1);
1515 appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1);
1525 public void mouseEntered(MouseEvent e)
1532 if (scrollThread != null)
1534 scrollThread.running = false;
1535 scrollThread = null;
1546 public void mouseExited(MouseEvent e)
1548 if (av.getWrapAlignment())
1555 scrollThread = new ScrollThread();
1560 * Handler for double-click on a position with one or more sequence features.
1561 * Opens the Amend Features dialog to allow feature details to be amended, or
1562 * the feature deleted.
1565 public void mouseClicked(MouseEvent evt)
1567 SequenceGroup sg = null;
1568 SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
1569 if (evt.getClickCount() > 1)
1571 sg = av.getSelectionGroup();
1572 if (sg != null && sg.getSize() == 1
1573 && sg.getEndRes() - sg.getStartRes() < 2)
1575 av.setSelectionGroup(null);
1578 int column = findColumn(evt);
1581 * find features at the position (if not gapped), or straddling
1582 * the position (if at a gap)
1584 List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1585 .findFeaturesAtColumn(sequence, column + 1);
1587 if (!features.isEmpty())
1590 * highlight the first feature at the position on the alignment
1592 SearchResultsI highlight = new SearchResults();
1593 highlight.addResult(sequence, features.get(0).getBegin(), features
1595 seqCanvas.highlightSearchResults(highlight);
1598 * open the Amend Features dialog; clear highlighting afterwards,
1599 * whether changes were made or not
1601 List<SequenceI> seqs = Collections.singletonList(sequence);
1602 seqCanvas.getFeatureRenderer().amendFeatures(seqs, features, false,
1604 seqCanvas.highlightSearchResults(null);
1610 public void mouseWheelMoved(MouseWheelEvent e)
1613 if (e.getWheelRotation() > 0)
1615 if (e.isShiftDown())
1617 av.getRanges().scrollRight(true);
1622 av.getRanges().scrollUp(false);
1627 if (e.isShiftDown())
1629 av.getRanges().scrollRight(false);
1633 av.getRanges().scrollUp(true);
1636 // TODO Update tooltip for new position.
1645 public void doMousePressedDefineMode(MouseEvent evt)
1647 final int res = findColumn(evt);
1648 final int seq = findSeq(evt);
1650 needOverviewUpdate = false;
1652 startWrapBlock = wrappedBlock;
1654 if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1656 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
1657 .getString("label.cannot_edit_annotations_in_wrapped_view"),
1658 MessageManager.getString("label.wrapped_view_no_edit"),
1659 JvOptionPane.WARNING_MESSAGE);
1663 if (seq < 0 || res < 0)
1668 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1670 if ((sequence == null) || (res > sequence.getLength()))
1675 stretchGroup = av.getSelectionGroup();
1677 if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1679 stretchGroup = av.getAlignment().findGroup(sequence, res);
1680 if (stretchGroup != null)
1682 // only update the current selection if the popup menu has a group to
1684 av.setSelectionGroup(stretchGroup);
1688 if (evt.isPopupTrigger()) // Mac: mousePressed
1695 * defer right-mouse click handling to mouseReleased on Windows
1696 * (where isPopupTrigger() will answer true)
1697 * NB isRightMouseButton is also true for Cmd-click on Mac
1699 if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1706 seqCanvas.cursorX = findColumn(evt);
1707 seqCanvas.cursorY = findSeq(evt);
1708 seqCanvas.repaint();
1712 if (stretchGroup == null)
1714 // Only if left mouse button do we want to change group sizes
1716 // define a new group here
1717 SequenceGroup sg = new SequenceGroup();
1718 sg.setStartRes(res);
1720 sg.addSequence(sequence, false);
1721 av.setSelectionGroup(sg);
1724 if (av.getConservationSelected())
1726 SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1730 if (av.getAbovePIDThreshold())
1732 SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1735 // TODO: stretchGroup will always be not null. Is this a merge error ?
1736 if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1738 // Edit end res position of selected group
1739 changeEndRes = true;
1741 else if ((stretchGroup != null)
1742 && (stretchGroup.getStartRes() == res))
1744 // Edit end res position of selected group
1745 changeStartRes = true;
1747 stretchGroup.getWidth();
1750 seqCanvas.repaint();
1754 * Build and show a pop-up menu at the right-click mouse position
1760 void showPopupMenu(MouseEvent evt)
1762 final int column = findColumn(evt);
1763 final int seq = findSeq(evt);
1764 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1765 List<SequenceFeature> allFeatures = ap.getFeatureRenderer()
1766 .findFeaturesAtColumn(sequence, column + 1);
1767 List<String> links = new ArrayList<>();
1768 for (SequenceFeature sf : allFeatures)
1770 if (sf.links != null)
1772 for (String link : sf.links)
1779 PopupMenu pop = new PopupMenu(ap, null, links);
1780 pop.show(this, evt.getX(), evt.getY());
1784 * Update the display after mouse up on a selection or group
1787 * mouse released event details
1789 * true if this event is happening after a mouse drag (rather than a
1792 public void doMouseReleasedDefineMode(MouseEvent evt, boolean afterDrag)
1794 if (stretchGroup == null)
1798 // always do this - annotation has own state
1799 // but defer colourscheme update until hidden sequences are passed in
1800 boolean vischange = stretchGroup.recalcConservation(true);
1801 needOverviewUpdate |= vischange && av.isSelectionDefinedGroup()
1803 if (stretchGroup.cs != null)
1805 stretchGroup.cs.alignmentChanged(stretchGroup,
1806 av.getHiddenRepSequences());
1808 ResidueShaderI groupColourScheme = stretchGroup.getGroupColourScheme();
1809 String name = stretchGroup.getName();
1810 if (stretchGroup.cs.conservationApplied())
1812 SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1814 if (stretchGroup.cs.getThreshold() > 0)
1816 SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1819 PaintRefresher.Refresh(this, av.getSequenceSetId());
1820 ap.paintAlignment(needOverviewUpdate);
1821 needOverviewUpdate = false;
1822 changeEndRes = false;
1823 changeStartRes = false;
1824 stretchGroup = null;
1834 public void doMouseDraggedDefineMode(MouseEvent evt)
1836 int res = findColumn(evt);
1837 int y = findSeq(evt);
1839 if (wrappedBlock != startWrapBlock)
1844 if (stretchGroup == null)
1849 if (res >= av.getAlignment().getWidth())
1851 res = av.getAlignment().getWidth() - 1;
1854 if (stretchGroup.getEndRes() == res)
1856 // Edit end res position of selected group
1857 changeEndRes = true;
1859 else if (stretchGroup.getStartRes() == res)
1861 // Edit start res position of selected group
1862 changeStartRes = true;
1865 if (res < av.getRanges().getStartRes())
1867 res = av.getRanges().getStartRes();
1872 if (res > (stretchGroup.getStartRes() - 1))
1874 stretchGroup.setEndRes(res);
1875 needOverviewUpdate |= av.isSelectionDefinedGroup();
1878 else if (changeStartRes)
1880 if (res < (stretchGroup.getEndRes() + 1))
1882 stretchGroup.setStartRes(res);
1883 needOverviewUpdate |= av.isSelectionDefinedGroup();
1887 int dragDirection = 0;
1893 else if (y < oldSeq)
1898 while ((y != oldSeq) && (oldSeq > -1)
1899 && (y < av.getAlignment().getHeight()))
1901 // This routine ensures we don't skip any sequences, as the
1902 // selection is quite slow.
1903 Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1905 oldSeq += dragDirection;
1912 Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1914 if (stretchGroup.getSequences(null).contains(nextSeq))
1916 stretchGroup.deleteSequence(seq, false);
1917 needOverviewUpdate |= av.isSelectionDefinedGroup();
1923 stretchGroup.addSequence(seq, false);
1926 stretchGroup.addSequence(nextSeq, false);
1927 needOverviewUpdate |= av.isSelectionDefinedGroup();
1936 mouseDragging = true;
1938 if (scrollThread != null)
1940 scrollThread.setEvent(evt);
1943 seqCanvas.repaint();
1946 void scrollCanvas(MouseEvent evt)
1950 if (scrollThread != null)
1952 scrollThread.running = false;
1953 scrollThread = null;
1955 mouseDragging = false;
1959 if (scrollThread == null)
1961 scrollThread = new ScrollThread();
1964 mouseDragging = true;
1965 scrollThread.setEvent(evt);
1970 // this class allows scrolling off the bottom of the visible alignment
1971 class ScrollThread extends Thread
1975 boolean running = false;
1977 public ScrollThread()
1982 public void setEvent(MouseEvent e)
1987 public void stopScrolling()
2001 if (mouseDragging && (evt.getY() < 0)
2002 && (av.getRanges().getStartSeq() > 0))
2004 running = av.getRanges().scrollUp(true);
2007 if (mouseDragging && (evt.getY() >= getHeight())
2008 && (av.getAlignment().getHeight() > av.getRanges()
2011 running = av.getRanges().scrollUp(false);
2014 if (mouseDragging && (evt.getX() < 0))
2016 running = av.getRanges().scrollRight(false);
2018 else if (mouseDragging && (evt.getX() >= getWidth()))
2020 running = av.getRanges().scrollRight(true);
2027 } catch (Exception ex)
2035 * modify current selection according to a received message.
2038 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
2039 HiddenColumns hidden, SelectionSource source)
2041 // TODO: fix this hack - source of messages is align viewport, but SeqPanel
2042 // handles selection messages...
2043 // TODO: extend config options to allow user to control if selections may be
2044 // shared between viewports.
2045 boolean iSentTheSelection = (av == source || (source instanceof AlignViewport && ((AlignmentViewport) source)
2046 .getSequenceSetId().equals(av.getSequenceSetId())));
2048 if (iSentTheSelection)
2050 // respond to our own event by updating dependent dialogs
2051 if (ap.getCalculationDialog() != null)
2053 ap.getCalculationDialog().validateCalcTypes();
2059 // process further ?
2060 if (!av.followSelection)
2066 * Ignore the selection if there is one of our own pending.
2068 if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
2074 * Check for selection in a view of which this one is a dna/protein
2077 if (selectionFromTranslation(seqsel, colsel, hidden, source))
2082 // do we want to thread this ? (contention with seqsel and colsel locks, I
2085 * only copy colsel if there is a real intersection between
2086 * sequence selection and this panel's alignment
2088 boolean repaint = false;
2089 boolean copycolsel = false;
2091 SequenceGroup sgroup = null;
2092 if (seqsel != null && seqsel.getSize() > 0)
2094 if (av.getAlignment() == null)
2096 Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2097 + " ViewId=" + av.getViewId()
2098 + " 's alignment is NULL! returning immediately.");
2101 sgroup = seqsel.intersect(av.getAlignment(),
2102 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2103 if ((sgroup != null && sgroup.getSize() > 0))
2108 if (sgroup != null && sgroup.getSize() > 0)
2110 av.setSelectionGroup(sgroup);
2114 av.setSelectionGroup(null);
2116 av.isSelectionGroupChanged(true);
2121 // the current selection is unset or from a previous message
2122 // so import the new colsel.
2123 if (colsel == null || colsel.isEmpty())
2125 if (av.getColumnSelection() != null)
2127 av.getColumnSelection().clear();
2133 // TODO: shift colSel according to the intersecting sequences
2134 if (av.getColumnSelection() == null)
2136 av.setColumnSelection(new ColumnSelection(colsel));
2140 av.getColumnSelection().setElementsFrom(colsel,
2141 av.getAlignment().getHiddenColumns());
2144 av.isColSelChanged(true);
2149 && av.hasHiddenColumns()
2150 && (av.getAlignment().getHiddenColumns() == null || av
2151 .getAlignment().getHiddenColumns().getHiddenRegions() == null))
2153 System.err.println("Bad things");
2155 if (repaint) // always true!
2157 // probably finessing with multiple redraws here
2158 PaintRefresher.Refresh(this, av.getSequenceSetId());
2159 // ap.paintAlignment(false);
2162 // lastly, update dependent dialogs
2163 if (ap.getCalculationDialog() != null)
2165 ap.getCalculationDialog().validateCalcTypes();
2171 * If this panel is a cdna/protein translation view of the selection source,
2172 * tries to map the source selection to a local one, and returns true. Else
2179 protected boolean selectionFromTranslation(SequenceGroup seqsel,
2180 ColumnSelection colsel, HiddenColumns hidden,
2181 SelectionSource source)
2183 if (!(source instanceof AlignViewportI))
2187 final AlignViewportI sourceAv = (AlignViewportI) source;
2188 if (sourceAv.getCodingComplement() != av
2189 && av.getCodingComplement() != sourceAv)
2195 * Map sequence selection
2197 SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2198 av.setSelectionGroup(sg);
2199 av.isSelectionGroupChanged(true);
2202 * Map column selection
2204 // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2206 ColumnSelection cs = new ColumnSelection();
2207 HiddenColumns hs = new HiddenColumns();
2208 MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2209 av.setColumnSelection(cs);
2210 av.getAlignment().setHiddenColumns(hs);
2212 // lastly, update any dependent dialogs
2213 if (ap.getCalculationDialog() != null)
2215 ap.getCalculationDialog().validateCalcTypes();
2218 PaintRefresher.Refresh(this, av.getSequenceSetId());