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() && pos != -1)
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,
865 * or -1 for a gapped column position.
868 * aligned sequence object
872 * index of sequence in alignment
873 * @return position of column in sequence or -1 if at a gap
875 int setStatusMessage(SequenceI sequence, final int column, int seq)
877 StringBuilder text = new StringBuilder(32);
880 * Sequence number (if known), and sequence name.
882 String seqno = seq == -1 ? "" : " " + (seq + 1);
883 text.append("Sequence").append(seqno).append(" ID: ")
884 .append(sequence.getName());
886 String residue = null;
888 * Try to translate the display character to residue name (null for gap).
890 final String displayChar = String.valueOf(sequence.getCharAt(column));
891 if (av.getAlignment().isNucleotide())
893 residue = ResidueProperties.nucleotideName.get(displayChar);
896 text.append(" Nucleotide: ").append(residue);
901 residue = "X".equalsIgnoreCase(displayChar) ? "X" : ("*"
902 .equals(displayChar) ? "STOP" : ResidueProperties.aa2Triplet
906 text.append(" Residue: ").append(residue);
913 pos = sequence.findPosition(column);
914 text.append(" (").append(Integer.toString(pos)).append(")");
916 ap.alignFrame.statusBar.setText(text.toString());
921 * Set the status bar message to highlight the first matched position in
926 private void setStatusMessage(SearchResultsI results)
928 AlignmentI al = this.av.getAlignment();
929 int sequenceIndex = al.findIndex(results);
930 if (sequenceIndex == -1)
934 SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
935 for (SearchResultMatchI m : results.getResults())
937 SequenceI seq = m.getSequence();
938 if (seq.getDatasetSequence() != null)
940 seq = seq.getDatasetSequence();
946 * Convert position in sequence (base 1) to sequence character array
949 int start = m.getStart() - m.getSequence().getStart();
950 setStatusMessage(seq, start, sequenceIndex);
960 public void mouseDragged(MouseEvent evt)
962 if (mouseWheelPressed)
964 boolean inSplitFrame = ap.av.getCodingComplement() != null;
965 boolean copyChanges = inSplitFrame && av.isProteinFontAsCdna();
967 int oldWidth = av.getCharWidth();
969 // Which is bigger, left-right or up-down?
970 if (Math.abs(evt.getY() - lastMousePress.getY()) > Math.abs(evt
971 .getX() - lastMousePress.getX()))
974 * on drag up or down, decrement or increment font size
976 int fontSize = av.font.getSize();
977 boolean fontChanged = false;
979 if (evt.getY() < lastMousePress.getY())
984 else if (evt.getY() > lastMousePress.getY())
997 Font newFont = new Font(av.font.getName(), av.font.getStyle(),
999 av.setFont(newFont, true);
1000 av.setCharWidth(oldWidth);
1004 ap.av.getCodingComplement().setFont(newFont, true);
1005 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1006 .getSplitViewContainer();
1007 splitFrame.adjustLayout();
1008 splitFrame.repaint();
1015 * on drag left or right, decrement or increment character width
1018 if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
1020 newWidth = av.getCharWidth() - 1;
1021 av.setCharWidth(newWidth);
1023 else if (evt.getX() > lastMousePress.getX())
1025 newWidth = av.getCharWidth() + 1;
1026 av.setCharWidth(newWidth);
1030 ap.paintAlignment(false);
1034 * need to ensure newWidth is set on cdna, regardless of which
1035 * panel the mouse drag happened in; protein will compute its
1036 * character width as 1:1 or 3:1
1038 av.getCodingComplement().setCharWidth(newWidth);
1039 SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1040 .getSplitViewContainer();
1041 splitFrame.adjustLayout();
1042 splitFrame.repaint();
1047 FontMetrics fm = getFontMetrics(av.getFont());
1048 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1050 lastMousePress = evt.getPoint();
1057 doMouseDraggedDefineMode(evt);
1061 int res = findColumn(evt);
1068 if ((lastres == -1) || (lastres == res))
1073 if ((res < av.getAlignment().getWidth()) && (res < lastres))
1075 // dragLeft, delete gap
1076 editSequence(false, false, res);
1080 editSequence(true, false, res);
1083 mouseDragging = true;
1084 if (scrollThread != null)
1086 scrollThread.setEvent(evt);
1090 // TODO: Make it more clever than many booleans
1091 synchronized void editSequence(boolean insertGap, boolean editSeq,
1095 int fixedRight = -1;
1096 boolean fixedColumns = false;
1097 SequenceGroup sg = av.getSelectionGroup();
1099 SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1101 // No group, but the sequence may represent a group
1102 if (!groupEditing && av.hasHiddenRows())
1104 if (av.isHiddenRepSequence(seq))
1106 sg = av.getRepresentedSequences(seq);
1107 groupEditing = true;
1111 StringBuilder message = new StringBuilder(64);
1114 message.append("Edit group:");
1115 if (editCommand == null)
1117 editCommand = new EditCommand(
1118 MessageManager.getString("action.edit_group"));
1123 message.append("Edit sequence: " + seq.getName());
1124 String label = seq.getName();
1125 if (label.length() > 10)
1127 label = label.substring(0, 10);
1129 if (editCommand == null)
1131 editCommand = new EditCommand(MessageManager.formatMessage(
1132 "label.edit_params", new String[] { label }));
1138 message.append(" insert ");
1142 message.append(" delete ");
1145 message.append(Math.abs(startres - lastres) + " gaps.");
1146 ap.alignFrame.statusBar.setText(message.toString());
1148 // Are we editing within a selection group?
1150 || (sg != null && sg.getSequences(av.getHiddenRepSequences())
1153 fixedColumns = true;
1155 // sg might be null as the user may only see 1 sequence,
1156 // but the sequence represents a group
1159 if (!av.isHiddenRepSequence(seq))
1164 sg = av.getRepresentedSequences(seq);
1167 fixedLeft = sg.getStartRes();
1168 fixedRight = sg.getEndRes();
1170 if ((startres < fixedLeft && lastres >= fixedLeft)
1171 || (startres >= fixedLeft && lastres < fixedLeft)
1172 || (startres > fixedRight && lastres <= fixedRight)
1173 || (startres <= fixedRight && lastres > fixedRight))
1179 if (fixedLeft > startres)
1181 fixedRight = fixedLeft - 1;
1184 else if (fixedRight < startres)
1186 fixedLeft = fixedRight;
1191 if (av.hasHiddenColumns())
1193 fixedColumns = true;
1194 int y1 = av.getAlignment().getHiddenColumns()
1195 .getHiddenBoundaryLeft(startres);
1196 int y2 = av.getAlignment().getHiddenColumns()
1197 .getHiddenBoundaryRight(startres);
1199 if ((insertGap && startres > y1 && lastres < y1)
1200 || (!insertGap && startres < y2 && lastres > y2))
1206 // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1207 // Selection spans a hidden region
1208 if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1216 fixedRight = y2 - 1;
1223 List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1224 int g, groupSize = vseqs.size();
1225 SequenceI[] groupSeqs = new SequenceI[groupSize];
1226 for (g = 0; g < groupSeqs.length; g++)
1228 groupSeqs[g] = vseqs.get(g);
1234 // If the user has selected the whole sequence, and is dragging to
1235 // the right, we can still extend the alignment and selectionGroup
1236 if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1237 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1239 sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1240 fixedRight = sg.getEndRes();
1243 // Is it valid with fixed columns??
1244 // Find the next gap before the end
1245 // of the visible region boundary
1246 boolean blank = false;
1247 for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1251 for (g = 0; g < groupSize; g++)
1253 for (int j = 0; j < startres - lastres; j++)
1255 if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1270 if (sg.getSize() == av.getAlignment().getHeight())
1272 if ((av.hasHiddenColumns() && startres < av.getAlignment()
1273 .getHiddenColumns().getHiddenBoundaryRight(startres)))
1279 int alWidth = av.getAlignment().getWidth();
1280 if (av.hasHiddenRows())
1282 int hwidth = av.getAlignment().getHiddenSequences()
1284 if (hwidth > alWidth)
1289 // We can still insert gaps if the selectionGroup
1290 // contains all the sequences
1291 sg.setEndRes(sg.getEndRes() + startres - lastres);
1292 fixedRight = alWidth + startres - lastres;
1303 else if (!insertGap)
1305 // / Are we able to delete?
1306 // ie are all columns blank?
1308 for (g = 0; g < groupSize; g++)
1310 for (int j = startres; j < lastres; j++)
1312 if (groupSeqs[g].getLength() <= j)
1317 if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1319 // Not a gap, block edit not valid
1329 // dragging to the right
1330 if (fixedColumns && fixedRight != -1)
1332 for (int j = lastres; j < startres; j++)
1334 insertChar(j, groupSeqs, fixedRight);
1339 appendEdit(Action.INSERT_GAP, groupSeqs, startres, startres
1345 // dragging to the left
1346 if (fixedColumns && fixedRight != -1)
1348 for (int j = lastres; j > startres; j--)
1350 deleteChar(startres, groupSeqs, fixedRight);
1355 appendEdit(Action.DELETE_GAP, groupSeqs, startres, lastres
1362 // ///Editing a single sequence///////////
1366 // dragging to the right
1367 if (fixedColumns && fixedRight != -1)
1369 for (int j = lastres; j < startres; j++)
1371 insertChar(j, new SequenceI[] { seq }, fixedRight);
1376 appendEdit(Action.INSERT_GAP, new SequenceI[] { seq }, lastres,
1377 startres - lastres);
1384 // dragging to the left
1385 if (fixedColumns && fixedRight != -1)
1387 for (int j = lastres; j > startres; j--)
1389 if (!Comparison.isGap(seq.getCharAt(startres)))
1394 deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1399 // could be a keyboard edit trying to delete none gaps
1401 for (int m = startres; m < lastres; m++)
1403 if (!Comparison.isGap(seq.getCharAt(m)))
1412 appendEdit(Action.DELETE_GAP, new SequenceI[] { seq },
1418 {// insertGap==false AND editSeq==TRUE;
1419 if (fixedColumns && fixedRight != -1)
1421 for (int j = lastres; j < startres; j++)
1423 insertChar(j, new SequenceI[] { seq }, fixedRight);
1428 appendEdit(Action.INSERT_NUC, new SequenceI[] { seq }, lastres,
1429 startres - lastres);
1436 seqCanvas.repaint();
1439 void insertChar(int j, SequenceI[] seq, int fixedColumn)
1441 int blankColumn = fixedColumn;
1442 for (int s = 0; s < seq.length; s++)
1444 // Find the next gap before the end of the visible region boundary
1445 // If lastCol > j, theres a boundary after the gap insertion
1447 for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1449 if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1451 // Theres a space, so break and insert the gap
1456 if (blankColumn <= j)
1458 blankColumn = fixedColumn;
1464 appendEdit(Action.DELETE_GAP, seq, blankColumn, 1);
1466 appendEdit(Action.INSERT_GAP, seq, j, 1);
1471 * Helper method to add and perform one edit action.
1478 protected void appendEdit(Action action, SequenceI[] seq, int pos,
1482 final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1483 av.getAlignment().getGapCharacter());
1485 editCommand.appendEdit(edit, av.getAlignment(), true, null);
1488 void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1491 appendEdit(Action.DELETE_GAP, seq, j, 1);
1493 appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1);
1503 public void mouseEntered(MouseEvent e)
1510 if (scrollThread != null)
1512 scrollThread.running = false;
1513 scrollThread = null;
1524 public void mouseExited(MouseEvent e)
1526 if (av.getWrapAlignment())
1533 scrollThread = new ScrollThread();
1538 * Handler for double-click on a position with one or more sequence features.
1539 * Opens the Amend Features dialog to allow feature details to be amended, or
1540 * the feature deleted.
1543 public void mouseClicked(MouseEvent evt)
1545 SequenceGroup sg = null;
1546 SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
1547 if (evt.getClickCount() > 1)
1549 sg = av.getSelectionGroup();
1550 if (sg != null && sg.getSize() == 1
1551 && sg.getEndRes() - sg.getStartRes() < 2)
1553 av.setSelectionGroup(null);
1556 List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1557 .findFeaturesAtRes(sequence.getDatasetSequence(),
1558 sequence.findPosition(findColumn(evt)));
1560 if (!features.isEmpty())
1563 * highlight the first feature at the position on the alignment
1565 SearchResultsI highlight = new SearchResults();
1566 highlight.addResult(sequence, features.get(0).getBegin(), features
1568 seqCanvas.highlightSearchResults(highlight);
1571 * open the Amend Features dialog; clear highlighting afterwards,
1572 * whether changes were made or not
1574 List<SequenceI> seqs = Collections.singletonList(sequence);
1575 seqCanvas.getFeatureRenderer().amendFeatures(seqs, features, false,
1577 seqCanvas.highlightSearchResults(null);
1583 public void mouseWheelMoved(MouseWheelEvent e)
1586 if (e.getWheelRotation() > 0)
1588 if (e.isShiftDown())
1590 ap.scrollRight(true);
1600 if (e.isShiftDown())
1602 ap.scrollRight(false);
1609 // TODO Update tooltip for new position.
1618 public void doMousePressedDefineMode(MouseEvent evt)
1620 final int res = findColumn(evt);
1621 final int seq = findSeq(evt);
1623 needOverviewUpdate = false;
1625 startWrapBlock = wrappedBlock;
1627 if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1629 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
1630 .getString("label.cannot_edit_annotations_in_wrapped_view"),
1631 MessageManager.getString("label.wrapped_view_no_edit"),
1632 JvOptionPane.WARNING_MESSAGE);
1636 if (seq < 0 || res < 0)
1641 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1643 if ((sequence == null) || (res > sequence.getLength()))
1648 stretchGroup = av.getSelectionGroup();
1650 if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1652 stretchGroup = av.getAlignment().findGroup(sequence, res);
1653 if (stretchGroup != null)
1655 // only update the current selection if the popup menu has a group to
1657 av.setSelectionGroup(stretchGroup);
1661 if (evt.isPopupTrigger()) // Mac: mousePressed
1668 * defer right-mouse click handling to mouseReleased on Windows
1669 * (where isPopupTrigger() will answer true)
1670 * NB isRightMouseButton is also true for Cmd-click on Mac
1672 if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1679 seqCanvas.cursorX = findColumn(evt);
1680 seqCanvas.cursorY = findSeq(evt);
1681 seqCanvas.repaint();
1685 if (stretchGroup == null)
1687 // Only if left mouse button do we want to change group sizes
1689 // define a new group here
1690 SequenceGroup sg = new SequenceGroup();
1691 sg.setStartRes(res);
1693 sg.addSequence(sequence, false);
1694 av.setSelectionGroup(sg);
1697 if (av.getConservationSelected())
1699 SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1703 if (av.getAbovePIDThreshold())
1705 SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1708 // TODO: stretchGroup will always be not null. Is this a merge error ?
1709 if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1711 // Edit end res position of selected group
1712 changeEndRes = true;
1714 else if ((stretchGroup != null)
1715 && (stretchGroup.getStartRes() == res))
1717 // Edit end res position of selected group
1718 changeStartRes = true;
1720 stretchGroup.getWidth();
1723 seqCanvas.repaint();
1727 * Build and show a pop-up menu at the right-click mouse position
1733 void showPopupMenu(MouseEvent evt)
1735 final int res = findColumn(evt);
1736 final int seq = findSeq(evt);
1737 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1738 List<SequenceFeature> allFeatures = ap.getFeatureRenderer()
1739 .findFeaturesAtRes(sequence.getDatasetSequence(),
1740 sequence.findPosition(res));
1741 List<String> links = new ArrayList<String>();
1742 for (SequenceFeature sf : allFeatures)
1744 if (sf.links != null)
1746 for (String link : sf.links)
1753 PopupMenu pop = new PopupMenu(ap, null, links);
1754 pop.show(this, evt.getX(), evt.getY());
1763 public void doMouseReleasedDefineMode(MouseEvent evt)
1765 if (stretchGroup == null)
1769 // always do this - annotation has own state
1770 // but defer colourscheme update until hidden sequences are passed in
1771 boolean vischange = stretchGroup.recalcConservation(true);
1772 needOverviewUpdate |= vischange && av.isSelectionDefinedGroup();
1773 if (stretchGroup.cs != null)
1775 stretchGroup.cs.alignmentChanged(stretchGroup,
1776 av.getHiddenRepSequences());
1778 ResidueShaderI groupColourScheme = stretchGroup.getGroupColourScheme();
1779 String name = stretchGroup.getName();
1780 if (stretchGroup.cs.conservationApplied())
1782 SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1784 if (stretchGroup.cs.getThreshold() > 0)
1786 SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1789 PaintRefresher.Refresh(this, av.getSequenceSetId());
1790 ap.paintAlignment(needOverviewUpdate);
1791 needOverviewUpdate = false;
1792 changeEndRes = false;
1793 changeStartRes = false;
1794 stretchGroup = null;
1804 public void doMouseDraggedDefineMode(MouseEvent evt)
1806 int res = findColumn(evt);
1807 int y = findSeq(evt);
1809 if (wrappedBlock != startWrapBlock)
1814 if (stretchGroup == null)
1819 if (res >= av.getAlignment().getWidth())
1821 res = av.getAlignment().getWidth() - 1;
1824 if (stretchGroup.getEndRes() == res)
1826 // Edit end res position of selected group
1827 changeEndRes = true;
1829 else if (stretchGroup.getStartRes() == res)
1831 // Edit start res position of selected group
1832 changeStartRes = true;
1835 if (res < av.getRanges().getStartRes())
1837 res = av.getRanges().getStartRes();
1842 if (res > (stretchGroup.getStartRes() - 1))
1844 stretchGroup.setEndRes(res);
1845 needOverviewUpdate |= av.isSelectionDefinedGroup();
1848 else if (changeStartRes)
1850 if (res < (stretchGroup.getEndRes() + 1))
1852 stretchGroup.setStartRes(res);
1853 needOverviewUpdate |= av.isSelectionDefinedGroup();
1857 int dragDirection = 0;
1863 else if (y < oldSeq)
1868 while ((y != oldSeq) && (oldSeq > -1)
1869 && (y < av.getAlignment().getHeight()))
1871 // This routine ensures we don't skip any sequences, as the
1872 // selection is quite slow.
1873 Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1875 oldSeq += dragDirection;
1882 Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1884 if (stretchGroup.getSequences(null).contains(nextSeq))
1886 stretchGroup.deleteSequence(seq, false);
1887 needOverviewUpdate |= av.isSelectionDefinedGroup();
1893 stretchGroup.addSequence(seq, false);
1896 stretchGroup.addSequence(nextSeq, false);
1897 needOverviewUpdate |= av.isSelectionDefinedGroup();
1906 mouseDragging = true;
1908 if (scrollThread != null)
1910 scrollThread.setEvent(evt);
1913 seqCanvas.repaint();
1916 void scrollCanvas(MouseEvent evt)
1920 if (scrollThread != null)
1922 scrollThread.running = false;
1923 scrollThread = null;
1925 mouseDragging = false;
1929 if (scrollThread == null)
1931 scrollThread = new ScrollThread();
1934 mouseDragging = true;
1935 scrollThread.setEvent(evt);
1940 // this class allows scrolling off the bottom of the visible alignment
1941 class ScrollThread extends Thread
1945 boolean running = false;
1947 public ScrollThread()
1952 public void setEvent(MouseEvent e)
1957 public void stopScrolling()
1971 if (mouseDragging && (evt.getY() < 0)
1972 && (av.getRanges().getStartSeq() > 0))
1974 running = ap.scrollUp(true);
1977 if (mouseDragging && (evt.getY() >= getHeight())
1978 && (av.getAlignment().getHeight() > av.getRanges()
1981 running = ap.scrollUp(false);
1984 if (mouseDragging && (evt.getX() < 0))
1986 running = ap.scrollRight(false);
1988 else if (mouseDragging && (evt.getX() >= getWidth()))
1990 running = ap.scrollRight(true);
1997 } catch (Exception ex)
2005 * modify current selection according to a received message.
2008 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
2009 HiddenColumns hidden, SelectionSource source)
2011 // TODO: fix this hack - source of messages is align viewport, but SeqPanel
2012 // handles selection messages...
2013 // TODO: extend config options to allow user to control if selections may be
2014 // shared between viewports.
2015 boolean iSentTheSelection = (av == source || (source instanceof AlignViewport && ((AlignmentViewport) source)
2016 .getSequenceSetId().equals(av.getSequenceSetId())));
2018 if (iSentTheSelection)
2020 // respond to our own event by updating dependent dialogs
2021 if (ap.getCalculationDialog() != null)
2023 ap.getCalculationDialog().validateCalcTypes();
2026 // process further ?
2027 if (!av.followSelection)
2034 * Ignore the selection if there is one of our own pending.
2036 if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
2042 * Check for selection in a view of which this one is a dna/protein
2045 if (selectionFromTranslation(seqsel, colsel, hidden, source))
2050 // do we want to thread this ? (contention with seqsel and colsel locks, I
2053 * only copy colsel if there is a real intersection between
2054 * sequence selection and this panel's alignment
2056 boolean repaint = false;
2057 boolean copycolsel = false;
2059 SequenceGroup sgroup = null;
2060 if (seqsel != null && seqsel.getSize() > 0)
2062 if (av.getAlignment() == null)
2064 Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2065 + " ViewId=" + av.getViewId()
2066 + " 's alignment is NULL! returning immediately.");
2069 sgroup = seqsel.intersect(av.getAlignment(),
2070 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2071 if ((sgroup != null && sgroup.getSize() > 0))
2076 if (sgroup != null && sgroup.getSize() > 0)
2078 av.setSelectionGroup(sgroup);
2082 av.setSelectionGroup(null);
2084 av.isSelectionGroupChanged(true);
2089 // the current selection is unset or from a previous message
2090 // so import the new colsel.
2091 if (colsel == null || colsel.isEmpty())
2093 if (av.getColumnSelection() != null)
2095 av.getColumnSelection().clear();
2101 // TODO: shift colSel according to the intersecting sequences
2102 if (av.getColumnSelection() == null)
2104 av.setColumnSelection(new ColumnSelection(colsel));
2108 av.getColumnSelection().setElementsFrom(colsel,
2109 av.getAlignment().getHiddenColumns());
2112 av.isColSelChanged(true);
2117 && av.hasHiddenColumns()
2118 && (av.getAlignment().getHiddenColumns() == null || av
2119 .getAlignment().getHiddenColumns().getHiddenRegions() == null))
2121 System.err.println("Bad things");
2123 if (repaint) // always true!
2125 // probably finessing with multiple redraws here
2126 PaintRefresher.Refresh(this, av.getSequenceSetId());
2127 // ap.paintAlignment(false);
2130 // lastly, update dependent dialogs
2131 if (ap.getCalculationDialog() != null)
2133 ap.getCalculationDialog().validateCalcTypes();
2139 * If this panel is a cdna/protein translation view of the selection source,
2140 * tries to map the source selection to a local one, and returns true. Else
2147 protected boolean selectionFromTranslation(SequenceGroup seqsel,
2148 ColumnSelection colsel, HiddenColumns hidden,
2149 SelectionSource source)
2151 if (!(source instanceof AlignViewportI))
2155 final AlignViewportI sourceAv = (AlignViewportI) source;
2156 if (sourceAv.getCodingComplement() != av
2157 && av.getCodingComplement() != sourceAv)
2163 * Map sequence selection
2165 SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2166 av.setSelectionGroup(sg);
2167 av.isSelectionGroupChanged(true);
2170 * Map column selection
2172 // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2174 ColumnSelection cs = new ColumnSelection();
2175 HiddenColumns hs = new HiddenColumns();
2176 MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2177 av.setColumnSelection(cs);
2178 av.getAlignment().setHiddenColumns(hs);
2180 // lastly, update any dependent dialogs
2181 if (ap.getCalculationDialog() != null)
2183 ap.getCalculationDialog().validateCalcTypes();
2186 PaintRefresher.Refresh(this, av.getSequenceSetId());