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.List;
65 import javax.swing.JPanel;
66 import javax.swing.SwingUtilities;
67 import javax.swing.ToolTipManager;
73 * @version $Revision: 1.130 $
75 public class SeqPanel extends JPanel implements MouseListener,
76 MouseMotionListener, MouseWheelListener, SequenceListener,
81 public SeqCanvas seqCanvas;
84 public AlignmentPanel ap;
86 protected int lastres;
88 protected int startseq;
90 protected AlignViewport av;
92 ScrollThread scrollThread = null;
94 boolean mouseDragging = false;
96 boolean editingSeqs = false;
98 boolean groupEditing = false;
100 // ////////////////////////////////////////
101 // ///Everything below this is for defining the boundary of the rubberband
102 // ////////////////////////////////////////
105 boolean changeEndSeq = false;
107 boolean changeStartSeq = false;
109 boolean changeEndRes = false;
111 boolean changeStartRes = false;
113 SequenceGroup stretchGroup = null;
115 boolean remove = false;
117 Point lastMousePress;
119 boolean mouseWheelPressed = false;
121 StringBuffer keyboardNo1;
123 StringBuffer keyboardNo2;
125 java.net.URL linkImageURL;
127 private final SequenceAnnotationReport seqARep;
129 StringBuilder tooltipText = new StringBuilder();
133 EditCommand editCommand;
135 StructureSelectionManager ssm;
137 SearchResultsI lastSearchResults;
140 * Creates a new SeqPanel object.
147 public SeqPanel(AlignViewport av, AlignmentPanel ap)
149 linkImageURL = getClass().getResource("/images/link.gif");
150 seqARep = new SequenceAnnotationReport(linkImageURL.toString());
151 ToolTipManager.sharedInstance().registerComponent(this);
152 ToolTipManager.sharedInstance().setInitialDelay(0);
153 ToolTipManager.sharedInstance().setDismissDelay(10000);
155 setBackground(Color.white);
157 seqCanvas = new SeqCanvas(ap);
158 setLayout(new BorderLayout());
159 add(seqCanvas, BorderLayout.CENTER);
165 addMouseMotionListener(this);
166 addMouseListener(this);
167 addMouseWheelListener(this);
168 ssm = av.getStructureSelectionManager();
169 ssm.addStructureViewerListener(this);
170 ssm.addSelectionListener(this);
174 int startWrapBlock = -1;
176 int wrappedBlock = -1;
179 * Returns the aligned sequence position (base 0) at the mouse position, or
180 * the closest visible one
185 int findRes(MouseEvent evt)
190 if (av.getWrapAlignment())
193 int hgap = av.getCharHeight();
194 if (av.getScaleAboveWrapped())
196 hgap += av.getCharHeight();
199 int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
200 + hgap + seqCanvas.getAnnotationHeight();
204 x -= seqCanvas.LABEL_WEST;
206 int cwidth = seqCanvas.getWrappedCanvasWidth(this.getWidth());
212 wrappedBlock = y / cHeight;
213 wrappedBlock += av.getRanges().getStartRes() / cwidth;
215 res = wrappedBlock * cwidth + x / av.getCharWidth();
220 if (x > seqCanvas.getX() + seqCanvas.getWidth())
222 // make sure we calculate relative to visible alignment, rather than
224 x = seqCanvas.getX() + seqCanvas.getWidth();
226 res = (x / av.getCharWidth()) + av.getRanges().getStartRes();
227 if (res > av.getRanges().getEndRes())
230 res = av.getRanges().getEndRes();
234 if (av.hasHiddenColumns())
236 res = av.getAlignment().getHiddenColumns()
237 .adjustForHiddenColumns(res);
244 int findSeq(MouseEvent evt)
249 if (av.getWrapAlignment())
251 int hgap = av.getCharHeight();
252 if (av.getScaleAboveWrapped())
254 hgap += av.getCharHeight();
257 int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
258 + hgap + seqCanvas.getAnnotationHeight();
262 seq = Math.min((y % cHeight) / av.getCharHeight(), av.getAlignment()
267 seq = Math.min((y / av.getCharHeight())
268 + av.getRanges().getStartSeq(),
270 .getAlignment().getHeight() - 1);
277 * When all of a sequence of edits are complete, put the resulting edit list
278 * on the history stack (undo list), and reset flags for editing in progress.
284 if (editCommand != null && editCommand.getSize() > 0)
286 ap.alignFrame.addHistoryItem(editCommand);
287 av.firePropertyChange("alignment", null, av.getAlignment()
293 * Tidy up come what may...
298 groupEditing = false;
307 seqCanvas.cursorY = getKeyboardNo1() - 1;
311 void setCursorColumn()
313 seqCanvas.cursorX = getKeyboardNo1() - 1;
317 void setCursorRowAndColumn()
319 if (keyboardNo2 == null)
321 keyboardNo2 = new StringBuffer();
325 seqCanvas.cursorX = getKeyboardNo1() - 1;
326 seqCanvas.cursorY = getKeyboardNo2() - 1;
331 void setCursorPosition()
333 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
335 seqCanvas.cursorX = sequence.findIndex(getKeyboardNo1()) - 1;
339 void moveCursor(int dx, int dy)
341 seqCanvas.cursorX += dx;
342 seqCanvas.cursorY += dy;
344 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
346 if (av.hasHiddenColumns()
347 && !hidden.isVisible(seqCanvas.cursorX))
349 int original = seqCanvas.cursorX - dx;
350 int maxWidth = av.getAlignment().getWidth();
352 while (!hidden.isVisible(seqCanvas.cursorX)
353 && seqCanvas.cursorX < maxWidth && seqCanvas.cursorX > 0)
355 seqCanvas.cursorX += dx;
358 if (seqCanvas.cursorX >= maxWidth
359 || !hidden.isVisible(seqCanvas.cursorX))
361 seqCanvas.cursorX = original;
368 void scrollToVisible()
370 if (seqCanvas.cursorX < 0)
372 seqCanvas.cursorX = 0;
374 else if (seqCanvas.cursorX > av.getAlignment().getWidth() - 1)
376 seqCanvas.cursorX = av.getAlignment().getWidth() - 1;
379 if (seqCanvas.cursorY < 0)
381 seqCanvas.cursorY = 0;
383 else if (seqCanvas.cursorY > av.getAlignment().getHeight() - 1)
385 seqCanvas.cursorY = av.getAlignment().getHeight() - 1;
389 if (av.getWrapAlignment())
391 ap.scrollToWrappedVisible(seqCanvas.cursorX);
395 while (seqCanvas.cursorY < av.getRanges().getStartSeq())
399 while (seqCanvas.cursorY + 1 > av.getRanges().getEndSeq())
403 if (!av.getWrapAlignment())
405 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
406 while (seqCanvas.cursorX < hidden.adjustForHiddenColumns(av
407 .getRanges().getStartRes()))
409 if (!ap.scrollRight(false))
414 while (seqCanvas.cursorX > hidden.adjustForHiddenColumns(av
415 .getRanges().getEndRes()))
417 if (!ap.scrollRight(true))
424 setStatusMessage(av.getAlignment().getSequenceAt(seqCanvas.cursorY),
425 seqCanvas.cursorX, seqCanvas.cursorY);
430 void setSelectionAreaAtCursor(boolean topLeft)
432 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
434 if (av.getSelectionGroup() != null)
436 SequenceGroup sg = av.getSelectionGroup();
437 // Find the top and bottom of this group
438 int min = av.getAlignment().getHeight(), max = 0;
439 for (int i = 0; i < sg.getSize(); i++)
441 int index = av.getAlignment().findIndex(sg.getSequenceAt(i));
456 sg.setStartRes(seqCanvas.cursorX);
457 if (sg.getEndRes() < seqCanvas.cursorX)
459 sg.setEndRes(seqCanvas.cursorX);
462 min = seqCanvas.cursorY;
466 sg.setEndRes(seqCanvas.cursorX);
467 if (sg.getStartRes() > seqCanvas.cursorX)
469 sg.setStartRes(seqCanvas.cursorX);
472 max = seqCanvas.cursorY + 1;
477 // Only the user can do this
478 av.setSelectionGroup(null);
482 // Now add any sequences between min and max
483 sg.getSequences(null).clear();
484 for (int i = min; i < max; i++)
486 sg.addSequence(av.getAlignment().getSequenceAt(i), false);
491 if (av.getSelectionGroup() == null)
493 SequenceGroup sg = new SequenceGroup();
494 sg.setStartRes(seqCanvas.cursorX);
495 sg.setEndRes(seqCanvas.cursorX);
496 sg.addSequence(sequence, false);
497 av.setSelectionGroup(sg);
500 ap.paintAlignment(false);
504 void insertGapAtCursor(boolean group)
506 groupEditing = group;
507 startseq = seqCanvas.cursorY;
508 lastres = seqCanvas.cursorX;
509 editSequence(true, false, seqCanvas.cursorX + getKeyboardNo1());
513 void deleteGapAtCursor(boolean group)
515 groupEditing = group;
516 startseq = seqCanvas.cursorY;
517 lastres = seqCanvas.cursorX + getKeyboardNo1();
518 editSequence(false, false, seqCanvas.cursorX);
522 void insertNucAtCursor(boolean group, String nuc)
524 // TODO not called - delete?
525 groupEditing = group;
526 startseq = seqCanvas.cursorY;
527 lastres = seqCanvas.cursorX;
528 editSequence(false, true, seqCanvas.cursorX + getKeyboardNo1());
532 void numberPressed(char value)
534 if (keyboardNo1 == null)
536 keyboardNo1 = new StringBuffer();
539 if (keyboardNo2 != null)
541 keyboardNo2.append(value);
545 keyboardNo1.append(value);
553 if (keyboardNo1 != null)
555 int value = Integer.parseInt(keyboardNo1.toString());
559 } catch (Exception x)
570 if (keyboardNo2 != null)
572 int value = Integer.parseInt(keyboardNo2.toString());
576 } catch (Exception x)
590 public void mouseReleased(MouseEvent evt)
592 mouseDragging = false;
593 mouseWheelPressed = false;
595 if (evt.isPopupTrigger()) // Windows: mouseReleased
604 doMouseReleasedDefineMode(evt);
618 public void mousePressed(MouseEvent evt)
620 lastMousePress = evt.getPoint();
622 if (SwingUtilities.isMiddleMouseButton(evt))
624 mouseWheelPressed = true;
628 boolean isControlDown = Platform.isControlDown(evt);
629 if (evt.isShiftDown() || isControlDown)
639 doMousePressedDefineMode(evt);
643 int seq = findSeq(evt);
644 int res = findRes(evt);
646 if (seq < 0 || res < 0)
651 if ((seq < av.getAlignment().getHeight())
652 && (res < av.getAlignment().getSequenceAt(seq).getLength()))
669 public void mouseOverSequence(SequenceI sequence, int index, int pos)
671 String tmp = sequence.hashCode() + " " + index + " " + pos;
673 if (lastMessage == null || !lastMessage.equals(tmp))
675 // System.err.println("mouseOver Sequence: "+tmp);
676 ssm.mouseOverSequence(sequence, index, pos, av);
682 * Highlight the mapped region described by the search results object (unless
683 * unchanged). This supports highlight of protein while mousing over linked
684 * cDNA and vice versa. The status bar is also updated to show the location of
685 * the start of the highlighted region.
688 public void highlightSequence(SearchResultsI results)
690 if (results == null || results.equals(lastSearchResults))
694 lastSearchResults = results;
696 if (av.isFollowHighlight())
699 * if scrollToPosition requires a scroll adjustment, this flag prevents
700 * another scroll event being propagated back to the originator
702 * @see AlignmentPanel#adjustmentValueChanged
704 ap.setDontScrollComplement(true);
705 if (ap.scrollToPosition(results, false))
707 seqCanvas.revalidate();
710 setStatusMessage(results);
711 seqCanvas.highlightSearchResults(results);
715 public VamsasSource getVamsasSource()
717 return this.ap == null ? null : this.ap.av;
721 public void updateColours(SequenceI seq, int index)
723 System.out.println("update the seqPanel colours");
734 public void mouseMoved(MouseEvent evt)
738 // This is because MacOSX creates a mouseMoved
739 // If control is down, other platforms will not.
743 int res = findRes(evt);
744 int seq = findSeq(evt);
746 if (res < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
751 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
753 if (res >= sequence.getLength())
758 pos = setStatusMessage(sequence, res, seq);
759 if (ssm != null && pos > -1)
761 mouseOverSequence(sequence, res, 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() <= res && groups[g].getEndRes() >= res)
773 if (!groups[g].getName().startsWith("JTreeGroup")
774 && !groups[g].getName().startsWith("JGroup"))
776 tooltipText.append(groups[g].getName());
779 if (groups[g].getDescription() != null)
781 tooltipText.append(": " + groups[g].getDescription());
787 // use aa to see if the mouse pointer is on a
788 if (av.isShowSequenceFeatures())
791 List<SequenceFeature> features = ap.getFeatureRenderer()
792 .findFeaturesAtRes(sequence.getDatasetSequence(),
793 rpos = sequence.findPosition(res));
794 seqARep.appendFeatures(tooltipText, rpos, features,
795 this.ap.getSeqPanel().seqCanvas.fr.getMinMax());
797 if (tooltipText.length() == 6) // <html>
799 setToolTipText(null);
804 if (lastTooltip == null
805 || !lastTooltip.equals(tooltipText.toString()))
807 String formatedTooltipText = JvSwingUtils.wrapTooltip(true,
808 tooltipText.toString());
809 // String formatedTooltipText = tooltipText.toString();
810 setToolTipText(formatedTooltipText);
811 lastTooltip = tooltipText.toString();
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 * Set status message in alignment panel
864 * aligned sequence object
868 * index of sequence in alignment
869 * @return position of res in sequence
871 int setStatusMessage(SequenceI sequence, int res, int seq)
873 StringBuilder text = new StringBuilder(32);
876 * Sequence number (if known), and sequence name.
878 String seqno = seq == -1 ? "" : " " + (seq + 1);
879 text.append("Sequence").append(seqno).append(" ID: ")
880 .append(sequence.getName());
882 String residue = null;
884 * Try to translate the display character to residue name (null for gap).
886 final String displayChar = String.valueOf(sequence.getCharAt(res));
887 if (av.getAlignment().isNucleotide())
889 residue = ResidueProperties.nucleotideName.get(displayChar);
892 text.append(" Nucleotide: ").append(residue);
897 residue = "X".equalsIgnoreCase(displayChar) ? "X" : ("*"
898 .equals(displayChar) ? "STOP" : ResidueProperties.aa2Triplet
902 text.append(" Residue: ").append(residue);
909 pos = sequence.findPosition(res);
910 text.append(" (").append(Integer.toString(pos)).append(")");
912 ap.alignFrame.statusBar.setText(text.toString());
917 * Set the status bar message to highlight the first matched position in
922 private void setStatusMessage(SearchResultsI results)
924 AlignmentI al = this.av.getAlignment();
925 int sequenceIndex = al.findIndex(results);
926 if (sequenceIndex == -1)
930 SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
931 for (SearchResultMatchI m : results.getResults())
933 SequenceI seq = m.getSequence();
934 if (seq.getDatasetSequence() != null)
936 seq = seq.getDatasetSequence();
942 * Convert position in sequence (base 1) to sequence character array
945 int start = m.getStart() - m.getSequence().getStart();
946 setStatusMessage(seq, start, sequenceIndex);
959 public void mouseDragged(MouseEvent evt)
961 if (mouseWheelPressed)
963 int oldWidth = av.getCharWidth();
965 // Which is bigger, left-right or up-down?
966 if (Math.abs(evt.getY() - lastMousePress.getY()) > Math.abs(evt
967 .getX() - lastMousePress.getX()))
969 int fontSize = av.font.getSize();
971 if (evt.getY() < lastMousePress.getY())
975 else if (evt.getY() > lastMousePress.getY())
986 new Font(av.font.getName(), av.font.getStyle(), fontSize),
988 av.setCharWidth(oldWidth);
993 if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
995 av.setCharWidth(av.getCharWidth() - 1);
997 else if (evt.getX() > lastMousePress.getX())
999 av.setCharWidth(av.getCharWidth() + 1);
1002 ap.paintAlignment(false);
1005 FontMetrics fm = getFontMetrics(av.getFont());
1006 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1008 lastMousePress = evt.getPoint();
1015 doMouseDraggedDefineMode(evt);
1019 int res = findRes(evt);
1026 if ((lastres == -1) || (lastres == res))
1031 if ((res < av.getAlignment().getWidth()) && (res < lastres))
1033 // dragLeft, delete gap
1034 editSequence(false, false, res);
1038 editSequence(true, false, res);
1041 mouseDragging = true;
1042 if (scrollThread != null)
1044 scrollThread.setEvent(evt);
1048 // TODO: Make it more clever than many booleans
1049 synchronized void editSequence(boolean insertGap, boolean editSeq,
1053 int fixedRight = -1;
1054 boolean fixedColumns = false;
1055 SequenceGroup sg = av.getSelectionGroup();
1057 SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1059 // No group, but the sequence may represent a group
1060 if (!groupEditing && av.hasHiddenRows())
1062 if (av.isHiddenRepSequence(seq))
1064 sg = av.getRepresentedSequences(seq);
1065 groupEditing = true;
1069 StringBuilder message = new StringBuilder(64);
1072 message.append("Edit group:");
1073 if (editCommand == null)
1075 editCommand = new EditCommand(
1076 MessageManager.getString("action.edit_group"));
1081 message.append("Edit sequence: " + seq.getName());
1082 String label = seq.getName();
1083 if (label.length() > 10)
1085 label = label.substring(0, 10);
1087 if (editCommand == null)
1089 editCommand = new EditCommand(MessageManager.formatMessage(
1090 "label.edit_params", new String[] { label }));
1096 message.append(" insert ");
1100 message.append(" delete ");
1103 message.append(Math.abs(startres - lastres) + " gaps.");
1104 ap.alignFrame.statusBar.setText(message.toString());
1106 // Are we editing within a selection group?
1108 || (sg != null && sg.getSequences(av.getHiddenRepSequences())
1111 fixedColumns = true;
1113 // sg might be null as the user may only see 1 sequence,
1114 // but the sequence represents a group
1117 if (!av.isHiddenRepSequence(seq))
1122 sg = av.getRepresentedSequences(seq);
1125 fixedLeft = sg.getStartRes();
1126 fixedRight = sg.getEndRes();
1128 if ((startres < fixedLeft && lastres >= fixedLeft)
1129 || (startres >= fixedLeft && lastres < fixedLeft)
1130 || (startres > fixedRight && lastres <= fixedRight)
1131 || (startres <= fixedRight && lastres > fixedRight))
1137 if (fixedLeft > startres)
1139 fixedRight = fixedLeft - 1;
1142 else if (fixedRight < startres)
1144 fixedLeft = fixedRight;
1149 if (av.hasHiddenColumns())
1151 fixedColumns = true;
1152 int y1 = av.getAlignment().getHiddenColumns()
1153 .getHiddenBoundaryLeft(startres);
1154 int y2 = av.getAlignment().getHiddenColumns()
1155 .getHiddenBoundaryRight(startres);
1157 if ((insertGap && startres > y1 && lastres < y1)
1158 || (!insertGap && startres < y2 && lastres > y2))
1164 // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1165 // Selection spans a hidden region
1166 if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1174 fixedRight = y2 - 1;
1181 List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1182 int g, groupSize = vseqs.size();
1183 SequenceI[] groupSeqs = new SequenceI[groupSize];
1184 for (g = 0; g < groupSeqs.length; g++)
1186 groupSeqs[g] = vseqs.get(g);
1192 // If the user has selected the whole sequence, and is dragging to
1193 // the right, we can still extend the alignment and selectionGroup
1194 if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1195 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1197 sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1198 fixedRight = sg.getEndRes();
1201 // Is it valid with fixed columns??
1202 // Find the next gap before the end
1203 // of the visible region boundary
1204 boolean blank = false;
1205 for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1209 for (g = 0; g < groupSize; g++)
1211 for (int j = 0; j < startres - lastres; j++)
1213 if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1228 if (sg.getSize() == av.getAlignment().getHeight())
1230 if ((av.hasHiddenColumns() && startres < av.getAlignment()
1231 .getHiddenColumns().getHiddenBoundaryRight(startres)))
1237 int alWidth = av.getAlignment().getWidth();
1238 if (av.hasHiddenRows())
1240 int hwidth = av.getAlignment().getHiddenSequences()
1242 if (hwidth > alWidth)
1247 // We can still insert gaps if the selectionGroup
1248 // contains all the sequences
1249 sg.setEndRes(sg.getEndRes() + startres - lastres);
1250 fixedRight = alWidth + startres - lastres;
1261 else if (!insertGap)
1263 // / Are we able to delete?
1264 // ie are all columns blank?
1266 for (g = 0; g < groupSize; g++)
1268 for (int j = startres; j < lastres; j++)
1270 if (groupSeqs[g].getLength() <= j)
1275 if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1277 // Not a gap, block edit not valid
1287 // dragging to the right
1288 if (fixedColumns && fixedRight != -1)
1290 for (int j = lastres; j < startres; j++)
1292 insertChar(j, groupSeqs, fixedRight);
1297 appendEdit(Action.INSERT_GAP, groupSeqs, startres, startres
1303 // dragging to the left
1304 if (fixedColumns && fixedRight != -1)
1306 for (int j = lastres; j > startres; j--)
1308 deleteChar(startres, groupSeqs, fixedRight);
1313 appendEdit(Action.DELETE_GAP, groupSeqs, startres, lastres
1320 // ///Editing a single sequence///////////
1324 // dragging to the right
1325 if (fixedColumns && fixedRight != -1)
1327 for (int j = lastres; j < startres; j++)
1329 insertChar(j, new SequenceI[] { seq }, fixedRight);
1334 appendEdit(Action.INSERT_GAP, new SequenceI[] { seq }, lastres,
1335 startres - lastres);
1342 // dragging to the left
1343 if (fixedColumns && fixedRight != -1)
1345 for (int j = lastres; j > startres; j--)
1347 if (!Comparison.isGap(seq.getCharAt(startres)))
1352 deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1357 // could be a keyboard edit trying to delete none gaps
1359 for (int m = startres; m < lastres; m++)
1361 if (!Comparison.isGap(seq.getCharAt(m)))
1370 appendEdit(Action.DELETE_GAP, new SequenceI[] { seq },
1376 {// insertGap==false AND editSeq==TRUE;
1377 if (fixedColumns && fixedRight != -1)
1379 for (int j = lastres; j < startres; j++)
1381 insertChar(j, new SequenceI[] { seq }, fixedRight);
1386 appendEdit(Action.INSERT_NUC, new SequenceI[] { seq }, lastres,
1387 startres - lastres);
1394 seqCanvas.repaint();
1397 void insertChar(int j, SequenceI[] seq, int fixedColumn)
1399 int blankColumn = fixedColumn;
1400 for (int s = 0; s < seq.length; s++)
1402 // Find the next gap before the end of the visible region boundary
1403 // If lastCol > j, theres a boundary after the gap insertion
1405 for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1407 if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1409 // Theres a space, so break and insert the gap
1414 if (blankColumn <= j)
1416 blankColumn = fixedColumn;
1422 appendEdit(Action.DELETE_GAP, seq, blankColumn, 1);
1424 appendEdit(Action.INSERT_GAP, seq, j, 1);
1429 * Helper method to add and perform one edit action.
1436 protected void appendEdit(Action action, SequenceI[] seq, int pos,
1440 final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1441 av.getAlignment().getGapCharacter());
1443 editCommand.appendEdit(edit, av.getAlignment(), true, null);
1446 void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1449 appendEdit(Action.DELETE_GAP, seq, j, 1);
1451 appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1);
1461 public void mouseEntered(MouseEvent e)
1468 if (scrollThread != null)
1470 scrollThread.running = false;
1471 scrollThread = null;
1482 public void mouseExited(MouseEvent e)
1484 if (av.getWrapAlignment())
1491 scrollThread = new ScrollThread();
1496 public void mouseClicked(MouseEvent evt)
1498 SequenceGroup sg = null;
1499 SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
1500 if (evt.getClickCount() > 1)
1502 sg = av.getSelectionGroup();
1503 if (sg != null && sg.getSize() == 1
1504 && sg.getEndRes() - sg.getStartRes() < 2)
1506 av.setSelectionGroup(null);
1509 List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1510 .findFeaturesAtRes(sequence.getDatasetSequence(),
1511 sequence.findPosition(findRes(evt)));
1513 if (features != null && features.size() > 0)
1515 SearchResultsI highlight = new SearchResults();
1516 highlight.addResult(sequence, features.get(0).getBegin(), features
1518 seqCanvas.highlightSearchResults(highlight);
1520 if (features != null && features.size() > 0)
1522 seqCanvas.getFeatureRenderer().amendFeatures(
1523 new SequenceI[] { sequence },
1524 features.toArray(new SequenceFeature[features.size()]),
1527 seqCanvas.highlightSearchResults(null);
1533 public void mouseWheelMoved(MouseWheelEvent e)
1536 if (e.getWheelRotation() > 0)
1538 if (e.isShiftDown())
1540 ap.scrollRight(true);
1550 if (e.isShiftDown())
1552 ap.scrollRight(false);
1559 // TODO Update tooltip for new position.
1568 public void doMousePressedDefineMode(MouseEvent evt)
1570 final int res = findRes(evt);
1571 final int seq = findSeq(evt);
1573 needOverviewUpdate = false;
1575 startWrapBlock = wrappedBlock;
1577 if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1579 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
1580 .getString("label.cannot_edit_annotations_in_wrapped_view"),
1581 MessageManager.getString("label.wrapped_view_no_edit"),
1582 JvOptionPane.WARNING_MESSAGE);
1586 if (seq < 0 || res < 0)
1591 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1593 if ((sequence == null) || (res > sequence.getLength()))
1598 stretchGroup = av.getSelectionGroup();
1600 if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1602 stretchGroup = av.getAlignment().findGroup(sequence, res);
1603 if (stretchGroup != null)
1605 // only update the current selection if the popup menu has a group to
1607 av.setSelectionGroup(stretchGroup);
1611 if (evt.isPopupTrigger()) // Mac: mousePressed
1618 * defer right-mouse click handling to mouseReleased on Windows
1619 * (where isPopupTrigger() will answer true)
1620 * NB isRightMouseButton is also true for Cmd-click on Mac
1622 if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1629 seqCanvas.cursorX = findRes(evt);
1630 seqCanvas.cursorY = findSeq(evt);
1631 seqCanvas.repaint();
1635 if (stretchGroup == null)
1637 // Only if left mouse button do we want to change group sizes
1639 // define a new group here
1640 SequenceGroup sg = new SequenceGroup();
1641 sg.setStartRes(res);
1643 sg.addSequence(sequence, false);
1644 av.setSelectionGroup(sg);
1647 if (av.getConservationSelected())
1649 SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1653 if (av.getAbovePIDThreshold())
1655 SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1658 // TODO: stretchGroup will always be not null. Is this a merge error ?
1659 if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1661 // Edit end res position of selected group
1662 changeEndRes = true;
1664 else if ((stretchGroup != null)
1665 && (stretchGroup.getStartRes() == res))
1667 // Edit end res position of selected group
1668 changeStartRes = true;
1670 stretchGroup.getWidth();
1673 seqCanvas.repaint();
1677 * Build and show a pop-up menu at the right-click mouse position
1683 void showPopupMenu(MouseEvent evt)
1685 final int res = findRes(evt);
1686 final int seq = findSeq(evt);
1687 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1688 List<SequenceFeature> allFeatures = ap.getFeatureRenderer()
1689 .findFeaturesAtRes(sequence.getDatasetSequence(),
1690 sequence.findPosition(res));
1691 List<String> links = new ArrayList<String>();
1692 for (SequenceFeature sf : allFeatures)
1694 if (sf.links != null)
1696 for (String link : sf.links)
1703 PopupMenu pop = new PopupMenu(ap, null, links);
1704 pop.show(this, evt.getX(), evt.getY());
1713 public void doMouseReleasedDefineMode(MouseEvent evt)
1715 if (stretchGroup == null)
1719 // always do this - annotation has own state
1720 // but defer colourscheme update until hidden sequences are passed in
1721 boolean vischange = stretchGroup.recalcConservation(true);
1722 needOverviewUpdate |= vischange && av.isSelectionDefinedGroup();
1723 if (stretchGroup.cs != null)
1725 stretchGroup.cs.alignmentChanged(stretchGroup,
1726 av.getHiddenRepSequences());
1728 ResidueShaderI groupColourScheme = stretchGroup.getGroupColourScheme();
1729 String name = stretchGroup.getName();
1730 if (stretchGroup.cs.conservationApplied())
1732 SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1734 if (stretchGroup.cs.getThreshold() > 0)
1736 SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1739 PaintRefresher.Refresh(this, av.getSequenceSetId());
1740 ap.paintAlignment(needOverviewUpdate);
1741 needOverviewUpdate = false;
1742 changeEndRes = false;
1743 changeStartRes = false;
1744 stretchGroup = null;
1754 public void doMouseDraggedDefineMode(MouseEvent evt)
1756 int res = findRes(evt);
1757 int y = findSeq(evt);
1759 if (wrappedBlock != startWrapBlock)
1764 if (stretchGroup == null)
1769 if (res >= av.getAlignment().getWidth())
1771 res = av.getAlignment().getWidth() - 1;
1774 if (stretchGroup.getEndRes() == res)
1776 // Edit end res position of selected group
1777 changeEndRes = true;
1779 else if (stretchGroup.getStartRes() == res)
1781 // Edit start res position of selected group
1782 changeStartRes = true;
1785 if (res < av.getRanges().getStartRes())
1787 res = av.getRanges().getStartRes();
1792 if (res > (stretchGroup.getStartRes() - 1))
1794 stretchGroup.setEndRes(res);
1795 needOverviewUpdate |= av.isSelectionDefinedGroup();
1798 else if (changeStartRes)
1800 if (res < (stretchGroup.getEndRes() + 1))
1802 stretchGroup.setStartRes(res);
1803 needOverviewUpdate |= av.isSelectionDefinedGroup();
1807 int dragDirection = 0;
1813 else if (y < oldSeq)
1818 while ((y != oldSeq) && (oldSeq > -1)
1819 && (y < av.getAlignment().getHeight()))
1821 // This routine ensures we don't skip any sequences, as the
1822 // selection is quite slow.
1823 Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1825 oldSeq += dragDirection;
1832 Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1834 if (stretchGroup.getSequences(null).contains(nextSeq))
1836 stretchGroup.deleteSequence(seq, false);
1837 needOverviewUpdate |= av.isSelectionDefinedGroup();
1843 stretchGroup.addSequence(seq, false);
1846 stretchGroup.addSequence(nextSeq, false);
1847 needOverviewUpdate |= av.isSelectionDefinedGroup();
1856 mouseDragging = true;
1858 if (scrollThread != null)
1860 scrollThread.setEvent(evt);
1863 seqCanvas.repaint();
1866 void scrollCanvas(MouseEvent evt)
1870 if (scrollThread != null)
1872 scrollThread.running = false;
1873 scrollThread = null;
1875 mouseDragging = false;
1879 if (scrollThread == null)
1881 scrollThread = new ScrollThread();
1884 mouseDragging = true;
1885 scrollThread.setEvent(evt);
1890 // this class allows scrolling off the bottom of the visible alignment
1891 class ScrollThread extends Thread
1895 boolean running = false;
1897 public ScrollThread()
1902 public void setEvent(MouseEvent e)
1907 public void stopScrolling()
1921 if (mouseDragging && (evt.getY() < 0)
1922 && (av.getRanges().getStartSeq() > 0))
1924 running = ap.scrollUp(true);
1927 if (mouseDragging && (evt.getY() >= getHeight())
1928 && (av.getAlignment().getHeight() > av.getRanges()
1931 running = ap.scrollUp(false);
1934 if (mouseDragging && (evt.getX() < 0))
1936 running = ap.scrollRight(false);
1938 else if (mouseDragging && (evt.getX() >= getWidth()))
1940 running = ap.scrollRight(true);
1947 } catch (Exception ex)
1955 * modify current selection according to a received message.
1958 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
1959 HiddenColumns hidden, SelectionSource source)
1961 // TODO: fix this hack - source of messages is align viewport, but SeqPanel
1962 // handles selection messages...
1963 // TODO: extend config options to allow user to control if selections may be
1964 // shared between viewports.
1965 boolean iSentTheSelection = (av == source || (source instanceof AlignViewport && ((AlignmentViewport) source)
1966 .getSequenceSetId().equals(av.getSequenceSetId())));
1967 if (iSentTheSelection || !av.followSelection)
1973 * Ignore the selection if there is one of our own pending.
1975 if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
1981 * Check for selection in a view of which this one is a dna/protein
1984 if (selectionFromTranslation(seqsel, colsel, hidden, source))
1989 // do we want to thread this ? (contention with seqsel and colsel locks, I
1992 * only copy colsel if there is a real intersection between
1993 * sequence selection and this panel's alignment
1995 boolean repaint = false;
1996 boolean copycolsel = false;
1998 SequenceGroup sgroup = null;
1999 if (seqsel != null && seqsel.getSize() > 0)
2001 if (av.getAlignment() == null)
2003 Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2004 + " ViewId=" + av.getViewId()
2005 + " 's alignment is NULL! returning immediately.");
2008 sgroup = seqsel.intersect(av.getAlignment(),
2009 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2010 if ((sgroup != null && sgroup.getSize() > 0))
2015 if (sgroup != null && sgroup.getSize() > 0)
2017 av.setSelectionGroup(sgroup);
2021 av.setSelectionGroup(null);
2023 av.isSelectionGroupChanged(true);
2028 // the current selection is unset or from a previous message
2029 // so import the new colsel.
2030 if (colsel == null || colsel.isEmpty())
2032 if (av.getColumnSelection() != null)
2034 av.getColumnSelection().clear();
2040 // TODO: shift colSel according to the intersecting sequences
2041 if (av.getColumnSelection() == null)
2043 av.setColumnSelection(new ColumnSelection(colsel));
2047 av.getColumnSelection().setElementsFrom(colsel,
2048 av.getAlignment().getHiddenColumns());
2051 av.isColSelChanged(true);
2056 && av.hasHiddenColumns()
2057 && (av.getAlignment().getHiddenColumns() == null || av
2058 .getAlignment().getHiddenColumns().getHiddenRegions() == null))
2060 System.err.println("Bad things");
2062 if (repaint) // always true!
2064 // probably finessing with multiple redraws here
2065 PaintRefresher.Refresh(this, av.getSequenceSetId());
2066 // ap.paintAlignment(false);
2071 * If this panel is a cdna/protein translation view of the selection source,
2072 * tries to map the source selection to a local one, and returns true. Else
2079 protected boolean selectionFromTranslation(SequenceGroup seqsel,
2080 ColumnSelection colsel, HiddenColumns hidden,
2081 SelectionSource source)
2083 if (!(source instanceof AlignViewportI))
2087 final AlignViewportI sourceAv = (AlignViewportI) source;
2088 if (sourceAv.getCodingComplement() != av
2089 && av.getCodingComplement() != sourceAv)
2095 * Map sequence selection
2097 SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2098 av.setSelectionGroup(sg);
2099 av.isSelectionGroupChanged(true);
2102 * Map column selection
2104 // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2106 ColumnSelection cs = new ColumnSelection();
2107 HiddenColumns hs = new HiddenColumns();
2108 MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2109 av.setColumnSelection(cs);
2110 av.getAlignment().setHiddenColumns(hs);
2112 PaintRefresher.Refresh(this, av.getSequenceSetId());