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,
412 setStatusMessage(av.getAlignment().getSequenceAt(seqCanvas.cursorY),
413 seqCanvas.cursorX, seqCanvas.cursorY);
418 void setSelectionAreaAtCursor(boolean topLeft)
420 SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
422 if (av.getSelectionGroup() != null)
424 SequenceGroup sg = av.getSelectionGroup();
425 // Find the top and bottom of this group
426 int min = av.getAlignment().getHeight(), max = 0;
427 for (int i = 0; i < sg.getSize(); i++)
429 int index = av.getAlignment().findIndex(sg.getSequenceAt(i));
444 sg.setStartRes(seqCanvas.cursorX);
445 if (sg.getEndRes() < seqCanvas.cursorX)
447 sg.setEndRes(seqCanvas.cursorX);
450 min = seqCanvas.cursorY;
454 sg.setEndRes(seqCanvas.cursorX);
455 if (sg.getStartRes() > seqCanvas.cursorX)
457 sg.setStartRes(seqCanvas.cursorX);
460 max = seqCanvas.cursorY + 1;
465 // Only the user can do this
466 av.setSelectionGroup(null);
470 // Now add any sequences between min and max
471 sg.getSequences(null).clear();
472 for (int i = min; i < max; i++)
474 sg.addSequence(av.getAlignment().getSequenceAt(i), false);
479 if (av.getSelectionGroup() == null)
481 SequenceGroup sg = new SequenceGroup();
482 sg.setStartRes(seqCanvas.cursorX);
483 sg.setEndRes(seqCanvas.cursorX);
484 sg.addSequence(sequence, false);
485 av.setSelectionGroup(sg);
488 ap.paintAlignment(false);
492 void insertGapAtCursor(boolean group)
494 groupEditing = group;
495 startseq = seqCanvas.cursorY;
496 lastres = seqCanvas.cursorX;
497 editSequence(true, false, seqCanvas.cursorX + getKeyboardNo1());
501 void deleteGapAtCursor(boolean group)
503 groupEditing = group;
504 startseq = seqCanvas.cursorY;
505 lastres = seqCanvas.cursorX + getKeyboardNo1();
506 editSequence(false, false, seqCanvas.cursorX);
510 void insertNucAtCursor(boolean group, String nuc)
512 // TODO not called - delete?
513 groupEditing = group;
514 startseq = seqCanvas.cursorY;
515 lastres = seqCanvas.cursorX;
516 editSequence(false, true, seqCanvas.cursorX + getKeyboardNo1());
520 void numberPressed(char value)
522 if (keyboardNo1 == null)
524 keyboardNo1 = new StringBuffer();
527 if (keyboardNo2 != null)
529 keyboardNo2.append(value);
533 keyboardNo1.append(value);
541 if (keyboardNo1 != null)
543 int value = Integer.parseInt(keyboardNo1.toString());
547 } catch (Exception x)
558 if (keyboardNo2 != null)
560 int value = Integer.parseInt(keyboardNo2.toString());
564 } catch (Exception x)
578 public void mouseReleased(MouseEvent evt)
580 boolean didDrag = mouseDragging; // did we come here after a drag
581 mouseDragging = false;
582 mouseWheelPressed = false;
584 if (evt.isPopupTrigger()) // Windows: mouseReleased
593 doMouseReleasedDefineMode(evt, didDrag);
607 public void mousePressed(MouseEvent evt)
609 lastMousePress = evt.getPoint();
611 if (SwingUtilities.isMiddleMouseButton(evt))
613 mouseWheelPressed = true;
617 boolean isControlDown = Platform.isControlDown(evt);
618 if (evt.isShiftDown() || isControlDown)
628 doMousePressedDefineMode(evt);
632 int seq = findSeq(evt);
633 int res = findColumn(evt);
635 if (seq < 0 || res < 0)
640 if ((seq < av.getAlignment().getHeight())
641 && (res < av.getAlignment().getSequenceAt(seq).getLength()))
658 public void mouseOverSequence(SequenceI sequence, int index, int pos)
660 String tmp = sequence.hashCode() + " " + index + " " + pos;
662 if (lastMessage == null || !lastMessage.equals(tmp))
664 // System.err.println("mouseOver Sequence: "+tmp);
665 ssm.mouseOverSequence(sequence, index, pos, av);
671 * Highlight the mapped region described by the search results object (unless
672 * unchanged). This supports highlight of protein while mousing over linked
673 * cDNA and vice versa. The status bar is also updated to show the location of
674 * the start of the highlighted region.
677 public void highlightSequence(SearchResultsI results)
679 if (results == null || results.equals(lastSearchResults))
683 lastSearchResults = results;
685 if (av.isFollowHighlight())
687 // don't allow highlight of protein/cDNA to also scroll a complementary
688 // panel,as this sets up a feedback loop (scrolling panel 1 causes moused
689 // over residue to change abruptly, causing highlighted residue in panel 2
690 // to change, causing a scroll in panel 1 etc)
691 ap.setToScrollComplementPanel(false);
692 if (ap.scrollToPosition(results, false))
694 seqCanvas.revalidate();
696 ap.setToScrollComplementPanel(true);
698 setStatusMessage(results);
699 seqCanvas.highlightSearchResults(results);
703 public VamsasSource getVamsasSource()
705 return this.ap == null ? null : this.ap.av;
709 public void updateColours(SequenceI seq, int index)
711 System.out.println("update the seqPanel colours");
722 public void mouseMoved(MouseEvent evt)
726 // This is because MacOSX creates a mouseMoved
727 // If control is down, other platforms will not.
731 final int column = findColumn(evt);
732 int seq = findSeq(evt);
733 if (column < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
738 if (column == lastMouseColumn && seq == lastMouseSeq)
741 * just a pixel move without change of residue
745 lastMouseColumn = column;
748 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
750 if (column >= sequence.getLength())
756 * set status bar message, returning residue position in sequence
758 boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
759 final int pos = setStatusMessage(sequence, column, seq);
760 if (ssm != null && !isGapped)
762 mouseOverSequence(sequence, column, pos);
765 tooltipText.setLength(6); // Cuts the buffer back to <html>
767 SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
770 for (int g = 0; g < groups.length; g++)
772 if (groups[g].getStartRes() <= column
773 && groups[g].getEndRes() >= column)
775 if (!groups[g].getName().startsWith("JTreeGroup")
776 && !groups[g].getName().startsWith("JGroup"))
778 tooltipText.append(groups[g].getName());
781 if (groups[g].getDescription() != null)
783 tooltipText.append(": " + groups[g].getDescription());
790 * add any features at the position to the tooltip; if over a gap, only
791 * add features that straddle the gap (pos may be the residue before or
794 if (av.isShowSequenceFeatures())
796 List<SequenceFeature> features = ap.getFeatureRenderer()
797 .findFeaturesAtColumn(sequence, column + 1);
798 seqARep.appendFeatures(tooltipText, pos, features,
799 this.ap.getSeqPanel().seqCanvas.fr.getMinMax());
801 if (tooltipText.length() == 6) // <html>
803 setToolTipText(null);
808 String textString = tooltipText.toString();
809 if (lastTooltip == null || !lastTooltip.equals(textString))
811 String formattedTooltipText = JvSwingUtils.wrapTooltip(true,
813 setToolTipText(formattedTooltipText);
814 lastTooltip = textString;
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, and residue and residue position if not at a gap, for the
864 * given sequence and column position. Returns the residue position returned
865 * by Sequence.findPosition. Note this may be for the nearest adjacent residue
866 * if at a gapped position.
869 * aligned sequence object
873 * index of sequence in alignment
874 * @return sequence position of residue at column, or adjacent residue if at a
877 int setStatusMessage(SequenceI sequence, final int column, int seq)
879 StringBuilder text = new StringBuilder(32);
882 * Sequence number (if known), and sequence name.
884 String seqno = seq == -1 ? "" : " " + (seq + 1);
885 text.append("Sequence").append(seqno).append(" ID: ")
886 .append(sequence.getName());
888 String residue = null;
891 * Try to translate the display character to residue name (null for gap).
893 final String displayChar = String.valueOf(sequence.getCharAt(column));
894 boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
895 int pos = sequence.findPosition(column);
899 boolean nucleotide = av.getAlignment().isNucleotide();
902 residue = ResidueProperties.nucleotideName.get(displayChar);
906 residue = "X".equalsIgnoreCase(displayChar) ? "X" : ("*"
907 .equals(displayChar) ? "STOP"
908 : ResidueProperties.aa2Triplet.get(displayChar));
910 text.append(" ").append(nucleotide ? "Nucleotide" : "Residue")
911 .append(": ").append(residue == null ? displayChar : residue);
913 text.append(" (").append(Integer.toString(pos)).append(")");
915 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 int column = findColumn(evt);
1559 * find features at the position (if not gapped), or straddling
1560 * the position (if at a gap)
1562 List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1563 .findFeaturesAtColumn(sequence, column + 1);
1565 if (!features.isEmpty())
1568 * highlight the first feature at the position on the alignment
1570 SearchResultsI highlight = new SearchResults();
1571 highlight.addResult(sequence, features.get(0).getBegin(), features
1573 seqCanvas.highlightSearchResults(highlight);
1576 * open the Amend Features dialog; clear highlighting afterwards,
1577 * whether changes were made or not
1579 List<SequenceI> seqs = Collections.singletonList(sequence);
1580 seqCanvas.getFeatureRenderer().amendFeatures(seqs, features, false,
1582 seqCanvas.highlightSearchResults(null);
1588 public void mouseWheelMoved(MouseWheelEvent e)
1591 if (e.getWheelRotation() > 0)
1593 if (e.isShiftDown())
1595 av.getRanges().scrollRight(true);
1600 av.getRanges().scrollUp(false);
1605 if (e.isShiftDown())
1607 av.getRanges().scrollRight(false);
1611 av.getRanges().scrollUp(true);
1614 // TODO Update tooltip for new position.
1623 public void doMousePressedDefineMode(MouseEvent evt)
1625 final int res = findColumn(evt);
1626 final int seq = findSeq(evt);
1628 needOverviewUpdate = false;
1630 startWrapBlock = wrappedBlock;
1632 if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1634 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
1635 .getString("label.cannot_edit_annotations_in_wrapped_view"),
1636 MessageManager.getString("label.wrapped_view_no_edit"),
1637 JvOptionPane.WARNING_MESSAGE);
1641 if (seq < 0 || res < 0)
1646 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1648 if ((sequence == null) || (res > sequence.getLength()))
1653 stretchGroup = av.getSelectionGroup();
1655 if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1657 stretchGroup = av.getAlignment().findGroup(sequence, res);
1658 if (stretchGroup != null)
1660 // only update the current selection if the popup menu has a group to
1662 av.setSelectionGroup(stretchGroup);
1666 if (evt.isPopupTrigger()) // Mac: mousePressed
1673 * defer right-mouse click handling to mouseReleased on Windows
1674 * (where isPopupTrigger() will answer true)
1675 * NB isRightMouseButton is also true for Cmd-click on Mac
1677 if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1684 seqCanvas.cursorX = findColumn(evt);
1685 seqCanvas.cursorY = findSeq(evt);
1686 seqCanvas.repaint();
1690 if (stretchGroup == null)
1692 // Only if left mouse button do we want to change group sizes
1694 // define a new group here
1695 SequenceGroup sg = new SequenceGroup();
1696 sg.setStartRes(res);
1698 sg.addSequence(sequence, false);
1699 av.setSelectionGroup(sg);
1702 if (av.getConservationSelected())
1704 SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1708 if (av.getAbovePIDThreshold())
1710 SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1713 // TODO: stretchGroup will always be not null. Is this a merge error ?
1714 if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1716 // Edit end res position of selected group
1717 changeEndRes = true;
1719 else if ((stretchGroup != null)
1720 && (stretchGroup.getStartRes() == res))
1722 // Edit end res position of selected group
1723 changeStartRes = true;
1725 stretchGroup.getWidth();
1728 seqCanvas.repaint();
1732 * Build and show a pop-up menu at the right-click mouse position
1738 void showPopupMenu(MouseEvent evt)
1740 final int column = findColumn(evt);
1741 final int seq = findSeq(evt);
1742 SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1743 List<SequenceFeature> allFeatures = ap.getFeatureRenderer()
1744 .findFeaturesAtColumn(sequence, column + 1);
1745 List<String> links = new ArrayList<>();
1746 for (SequenceFeature sf : allFeatures)
1748 if (sf.links != null)
1750 for (String link : sf.links)
1757 PopupMenu pop = new PopupMenu(ap, null, links);
1758 pop.show(this, evt.getX(), evt.getY());
1762 * Update the display after mouse up on a selection or group
1765 * mouse released event details
1767 * true if this event is happening after a mouse drag (rather than a
1770 public void doMouseReleasedDefineMode(MouseEvent evt, boolean afterDrag)
1772 if (stretchGroup == null)
1776 // always do this - annotation has own state
1777 // but defer colourscheme update until hidden sequences are passed in
1778 boolean vischange = stretchGroup.recalcConservation(true);
1779 needOverviewUpdate |= vischange && av.isSelectionDefinedGroup()
1781 if (stretchGroup.cs != null)
1783 stretchGroup.cs.alignmentChanged(stretchGroup,
1784 av.getHiddenRepSequences());
1786 ResidueShaderI groupColourScheme = stretchGroup.getGroupColourScheme();
1787 String name = stretchGroup.getName();
1788 if (stretchGroup.cs.conservationApplied())
1790 SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1792 if (stretchGroup.cs.getThreshold() > 0)
1794 SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1797 PaintRefresher.Refresh(this, av.getSequenceSetId());
1798 ap.paintAlignment(needOverviewUpdate);
1799 needOverviewUpdate = false;
1800 changeEndRes = false;
1801 changeStartRes = false;
1802 stretchGroup = null;
1812 public void doMouseDraggedDefineMode(MouseEvent evt)
1814 int res = findColumn(evt);
1815 int y = findSeq(evt);
1817 if (wrappedBlock != startWrapBlock)
1822 if (stretchGroup == null)
1827 if (res >= av.getAlignment().getWidth())
1829 res = av.getAlignment().getWidth() - 1;
1832 if (stretchGroup.getEndRes() == res)
1834 // Edit end res position of selected group
1835 changeEndRes = true;
1837 else if (stretchGroup.getStartRes() == res)
1839 // Edit start res position of selected group
1840 changeStartRes = true;
1843 if (res < av.getRanges().getStartRes())
1845 res = av.getRanges().getStartRes();
1850 if (res > (stretchGroup.getStartRes() - 1))
1852 stretchGroup.setEndRes(res);
1853 needOverviewUpdate |= av.isSelectionDefinedGroup();
1856 else if (changeStartRes)
1858 if (res < (stretchGroup.getEndRes() + 1))
1860 stretchGroup.setStartRes(res);
1861 needOverviewUpdate |= av.isSelectionDefinedGroup();
1865 int dragDirection = 0;
1871 else if (y < oldSeq)
1876 while ((y != oldSeq) && (oldSeq > -1)
1877 && (y < av.getAlignment().getHeight()))
1879 // This routine ensures we don't skip any sequences, as the
1880 // selection is quite slow.
1881 Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1883 oldSeq += dragDirection;
1890 Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1892 if (stretchGroup.getSequences(null).contains(nextSeq))
1894 stretchGroup.deleteSequence(seq, false);
1895 needOverviewUpdate |= av.isSelectionDefinedGroup();
1901 stretchGroup.addSequence(seq, false);
1904 stretchGroup.addSequence(nextSeq, false);
1905 needOverviewUpdate |= av.isSelectionDefinedGroup();
1914 mouseDragging = true;
1916 if (scrollThread != null)
1918 scrollThread.setEvent(evt);
1921 seqCanvas.repaint();
1924 void scrollCanvas(MouseEvent evt)
1928 if (scrollThread != null)
1930 scrollThread.running = false;
1931 scrollThread = null;
1933 mouseDragging = false;
1937 if (scrollThread == null)
1939 scrollThread = new ScrollThread();
1942 mouseDragging = true;
1943 scrollThread.setEvent(evt);
1948 // this class allows scrolling off the bottom of the visible alignment
1949 class ScrollThread extends Thread
1953 boolean running = false;
1955 public ScrollThread()
1960 public void setEvent(MouseEvent e)
1965 public void stopScrolling()
1979 if (mouseDragging && (evt.getY() < 0)
1980 && (av.getRanges().getStartSeq() > 0))
1982 running = av.getRanges().scrollUp(true);
1985 if (mouseDragging && (evt.getY() >= getHeight())
1986 && (av.getAlignment().getHeight() > av.getRanges()
1989 running = av.getRanges().scrollUp(false);
1992 if (mouseDragging && (evt.getX() < 0))
1994 running = av.getRanges().scrollRight(false);
1996 else if (mouseDragging && (evt.getX() >= getWidth()))
1998 running = av.getRanges().scrollRight(true);
2005 } catch (Exception ex)
2013 * modify current selection according to a received message.
2016 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
2017 HiddenColumns hidden, SelectionSource source)
2019 // TODO: fix this hack - source of messages is align viewport, but SeqPanel
2020 // handles selection messages...
2021 // TODO: extend config options to allow user to control if selections may be
2022 // shared between viewports.
2023 boolean iSentTheSelection = (av == source || (source instanceof AlignViewport && ((AlignmentViewport) source)
2024 .getSequenceSetId().equals(av.getSequenceSetId())));
2026 if (iSentTheSelection)
2028 // respond to our own event by updating dependent dialogs
2029 if (ap.getCalculationDialog() != null)
2031 ap.getCalculationDialog().validateCalcTypes();
2037 // process further ?
2038 if (!av.followSelection)
2044 * Ignore the selection if there is one of our own pending.
2046 if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
2052 * Check for selection in a view of which this one is a dna/protein
2055 if (selectionFromTranslation(seqsel, colsel, hidden, source))
2060 // do we want to thread this ? (contention with seqsel and colsel locks, I
2063 * only copy colsel if there is a real intersection between
2064 * sequence selection and this panel's alignment
2066 boolean repaint = false;
2067 boolean copycolsel = false;
2069 SequenceGroup sgroup = null;
2070 if (seqsel != null && seqsel.getSize() > 0)
2072 if (av.getAlignment() == null)
2074 Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2075 + " ViewId=" + av.getViewId()
2076 + " 's alignment is NULL! returning immediately.");
2079 sgroup = seqsel.intersect(av.getAlignment(),
2080 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2081 if ((sgroup != null && sgroup.getSize() > 0))
2086 if (sgroup != null && sgroup.getSize() > 0)
2088 av.setSelectionGroup(sgroup);
2092 av.setSelectionGroup(null);
2094 av.isSelectionGroupChanged(true);
2099 // the current selection is unset or from a previous message
2100 // so import the new colsel.
2101 if (colsel == null || colsel.isEmpty())
2103 if (av.getColumnSelection() != null)
2105 av.getColumnSelection().clear();
2111 // TODO: shift colSel according to the intersecting sequences
2112 if (av.getColumnSelection() == null)
2114 av.setColumnSelection(new ColumnSelection(colsel));
2118 av.getColumnSelection().setElementsFrom(colsel,
2119 av.getAlignment().getHiddenColumns());
2122 av.isColSelChanged(true);
2127 && av.hasHiddenColumns()
2128 && (av.getAlignment().getHiddenColumns() == null || av
2129 .getAlignment().getHiddenColumns().getHiddenRegions() == null))
2131 System.err.println("Bad things");
2133 if (repaint) // always true!
2135 // probably finessing with multiple redraws here
2136 PaintRefresher.Refresh(this, av.getSequenceSetId());
2137 // ap.paintAlignment(false);
2140 // lastly, update dependent dialogs
2141 if (ap.getCalculationDialog() != null)
2143 ap.getCalculationDialog().validateCalcTypes();
2149 * If this panel is a cdna/protein translation view of the selection source,
2150 * tries to map the source selection to a local one, and returns true. Else
2157 protected boolean selectionFromTranslation(SequenceGroup seqsel,
2158 ColumnSelection colsel, HiddenColumns hidden,
2159 SelectionSource source)
2161 if (!(source instanceof AlignViewportI))
2165 final AlignViewportI sourceAv = (AlignViewportI) source;
2166 if (sourceAv.getCodingComplement() != av
2167 && av.getCodingComplement() != sourceAv)
2173 * Map sequence selection
2175 SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2176 av.setSelectionGroup(sg);
2177 av.isSelectionGroupChanged(true);
2180 * Map column selection
2182 // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2184 ColumnSelection cs = new ColumnSelection();
2185 HiddenColumns hs = new HiddenColumns();
2186 MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2187 av.setColumnSelection(cs);
2188 av.getAlignment().setHiddenColumns(hs);
2190 // lastly, update any dependent dialogs
2191 if (ap.getCalculationDialog() != null)
2193 ap.getCalculationDialog().validateCalcTypes();
2196 PaintRefresher.Refresh(this, av.getSequenceSetId());