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.analysis.AlignSeq;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.ColumnSelection;
26 import jalview.datamodel.RnaViewerModel;
27 import jalview.datamodel.SequenceGroup;
28 import jalview.datamodel.SequenceI;
29 import jalview.ext.varna.RnaModel;
30 import jalview.structure.SecondaryStructureListener;
31 import jalview.structure.SelectionListener;
32 import jalview.structure.SelectionSource;
33 import jalview.structure.StructureSelectionManager;
34 import jalview.structure.VamsasSource;
35 import jalview.util.Comparison;
36 import jalview.util.MessageManager;
37 import jalview.util.ShiftList;
39 import java.awt.BorderLayout;
40 import java.awt.Color;
41 import java.util.Collection;
42 import java.util.Hashtable;
43 import java.util.LinkedHashMap;
44 import java.util.List;
47 import javax.swing.JInternalFrame;
48 import javax.swing.JSplitPane;
49 import javax.swing.event.InternalFrameAdapter;
50 import javax.swing.event.InternalFrameEvent;
52 import fr.orsay.lri.varna.VARNAPanel;
53 import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
54 import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
55 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
56 import fr.orsay.lri.varna.interfaces.InterfaceVARNASelectionListener;
57 import fr.orsay.lri.varna.models.BaseList;
58 import fr.orsay.lri.varna.models.FullBackup;
59 import fr.orsay.lri.varna.models.annotations.HighlightRegionAnnotation;
60 import fr.orsay.lri.varna.models.rna.ModeleBase;
61 import fr.orsay.lri.varna.models.rna.RNA;
63 public class AppVarna extends JInternalFrame implements SelectionListener,
64 SecondaryStructureListener, InterfaceVARNASelectionListener,
67 private static final byte[] PAIRS = new byte[]
68 { '(', ')', '[', ']', '{', '}', '<', '>' };
70 private AppVarnaBinding vab;
72 private AlignmentPanel ap;
74 private String viewId;
76 private StructureSelectionManager ssm;
79 * Lookup for sequence and annotation mapped to each RNA in the viewer. Using
80 * a linked hashmap means that order is preserved when saved to the project.
82 private Map<RNA, RnaModel> models = new LinkedHashMap<RNA, RnaModel>();
84 private Map<RNA, ShiftList> offsets = new Hashtable<RNA, ShiftList>();
86 private Map<RNA, ShiftList> offsetsInv = new Hashtable<RNA, ShiftList>();
88 private JSplitPane split;
90 private VarnaHighlighter mouseOverHighlighter = new VarnaHighlighter();
92 private VarnaHighlighter selectionHighlighter = new VarnaHighlighter();
94 private class VarnaHighlighter
96 private HighlightRegionAnnotation _lastHighlight;
98 private RNA _lastRNAhighlighted = null;
100 public VarnaHighlighter()
106 * Constructor when restoring from Varna session, including any highlight
111 public VarnaHighlighter(RNA rna)
113 // TODO nice try but doesn't work; do we need a highlighter per model?
114 _lastRNAhighlighted = rna;
115 List<HighlightRegionAnnotation> highlights = rna.getHighlightRegion();
116 if (highlights != null && !highlights.isEmpty())
118 _lastHighlight = highlights.get(0);
122 public void highlightRegion(RNA rna, int start, int end)
124 clearLastSelection();
125 HighlightRegionAnnotation highlight = new HighlightRegionAnnotation(
126 rna.getBasesBetween(start, end));
127 rna.addHighlightRegion(highlight);
128 _lastHighlight = highlight;
129 _lastRNAhighlighted = rna;
132 public HighlightRegionAnnotation getLastHighlight()
134 return _lastHighlight;
138 * Clears all structure selection and refreshes the display
140 public void clearSelection()
142 if (_lastRNAhighlighted != null)
144 _lastRNAhighlighted.getHighlightRegion().clear();
145 vab.updateSelectedRNA(_lastRNAhighlighted);
146 _lastRNAhighlighted = null;
147 _lastHighlight = null;
152 * Clear the last structure selection
154 public void clearLastSelection()
156 if (_lastRNAhighlighted != null)
158 _lastRNAhighlighted.removeHighlightRegion(_lastHighlight);
159 _lastRNAhighlighted = null;
160 _lastHighlight = null;
171 * the annotation with the secondary structure string
173 * the AlignmentPanel creating this object
175 public AppVarna(SequenceI seq, AlignmentAnnotation aa, AlignmentPanel ap)
179 String sname = aa.sequenceRef == null ? "secondary structure (alignment)"
180 : seq.getName() + " structure";
181 String theTitle = sname
182 + (aa.sequenceRef == null ? " trimmed to " + seq.getName() : "");
183 theTitle = MessageManager.formatMessage("label.varna_params",
188 String gappedTitle = sname + " (with gaps)";
189 RnaModel gappedModel = new RnaModel(gappedTitle, aa, seq, null, true);
190 addModel(gappedModel, gappedTitle);
192 String trimmedTitle = "trimmed " + sname;
193 RnaModel trimmedModel = new RnaModel(trimmedTitle, aa, seq, null, false);
194 addModel(trimmedModel, trimmedTitle);
195 vab.setSelectedIndex(0);
200 * Constructor that links the viewer to a parent panel (but has no structures
201 * yet - use addModel to add them)
205 protected AppVarna(AlignmentPanel ap)
208 this.viewId = System.currentTimeMillis() + "." + this.hashCode();
209 vab = new AppVarnaBinding();
212 this.ssm = ap.getStructureSelectionManager();
213 ssm.addStructureViewerListener(this);
214 ssm.addSelectionListener(this);
215 addInternalFrameListener(new InternalFrameAdapter()
218 public void internalFrameClosed(InternalFrameEvent evt)
226 * Constructor given viewer data read from a saved project file
230 * the (or a) parent alignment panel
232 public AppVarna(RnaViewerModel model, AlignmentPanel ap)
235 setTitle(model.title);
236 this.viewId = model.viewId;
237 setBounds(model.x, model.y, model.width, model.height);
238 this.split.setDividerLocation(model.dividerLocation);
242 * Constructs a split pane with an empty selection list and display panel, and
243 * adds it to the desktop
245 public void initVarna()
247 VARNAPanel varnaPanel = vab.get_varnaPanel();
248 setBackground(Color.white);
249 split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true,
250 vab.getListPanel(), varnaPanel);
251 getContentPane().setLayout(new BorderLayout());
252 getContentPane().add(split, BorderLayout.CENTER);
254 varnaPanel.addSelectionListener(this);
255 jalview.gui.Desktop.addInternalFrame(this, "", getBounds().width,
262 * Constructs a new RNA model from the given one, without gaps. Also
263 * calculates and saves a 'shift list'
269 public RNA trimRNA(RNA rna, String name)
271 ShiftList offset = new ShiftList();
273 RNA rnaTrim = new RNA(name);
276 String structDBN = rna.getStructDBN(true);
277 rnaTrim.setRNA(rna.getSeq(), replaceOddGaps(structDBN));
278 } catch (ExceptionUnmatchedClosingParentheses e2)
280 e2.printStackTrace();
281 } catch (ExceptionFileFormatOrSyntax e3)
283 e3.printStackTrace();
286 String seq = rnaTrim.getSeq();
287 StringBuilder struc = new StringBuilder(256);
288 struc.append(rnaTrim.getStructDBN(true));
290 int sleng = seq.length();
292 for (int i = 0; i < sleng; i++)
294 if (Comparison.isGap(seq.charAt(i)))
301 * mark base or base & pair in the structure with *
303 if (!rnaTrim.findPair(i).isEmpty())
305 int m = rnaTrim.findPair(i).get(1);
306 int l = rnaTrim.findPair(i).get(0);
308 struc.replace(m, m + 1, "*");
309 struc.replace(l, l + 1, "*");
313 struc.replace(i, i + 1, "*");
320 offset.addShift(offset.shift(ofstart), ofstart - i);
328 offset.addShift(offset.shift(ofstart), ofstart - sleng);
333 * remove the marked gaps from the structure
335 String newStruc = struc.toString().replace("*", "");
338 * remove gaps from the sequence
340 String newSeq = AlignSeq.extractGaps(Comparison.GapChars, seq);
344 rnaTrim.setRNA(newSeq, newStruc);
345 registerOffset(rnaTrim, offset);
346 } catch (ExceptionUnmatchedClosingParentheses e)
349 } catch (ExceptionFileFormatOrSyntax e)
357 * Save the sequence to structure mapping, and also its inverse.
362 private void registerOffset(RNA rnaTrim, ShiftList offset)
364 offsets.put(rnaTrim, offset);
365 offsetsInv.put(rnaTrim, offset.getInverse());
368 public void showPanel(boolean show)
370 this.setVisible(show);
374 * If a mouseOver event from the AlignmentPanel is noticed the currently
375 * selected RNA in the VARNA window is highlighted at the specific position.
376 * To be able to remove it before the next highlight it is saved in
381 * the aligned sequence position (base 0)
383 * the dataset sequence position (base 1)
386 public void mouseOverSequence(SequenceI sequence, final int index,
389 RNA rna = vab.getSelectedRNA();
394 RnaModel rnaModel = models.get(rna);
395 if (rnaModel.seq == sequence)
397 int highlightPos = rnaModel.gapped ? index : position - 1;
398 mouseOverHighlighter.highlightRegion(rna, highlightPos, highlightPos);
399 vab.updateSelectedRNA(rna);
404 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
405 SelectionSource source)
409 // ignore events from anything but our parent alignpanel
410 // TODO - reuse many-one panel-view system in jmol viewer
413 RNA rna = vab.getSelectedRNA();
418 if (seqsel != null && seqsel.getSize() > 0)
420 int start = seqsel.getStartRes(), end = seqsel.getEndRes();
421 ShiftList shift = offsets.get(rna);
424 start = shift.shift(start);
425 end = shift.shift(end);
427 selectionHighlighter.highlightRegion(rna, start, end);
428 selectionHighlighter.getLastHighlight().setOutlineColor(
429 seqsel.getOutlineColour());
430 // TODO - translate column markings to positions on structure if present.
431 vab.updateSelectedRNA(rna);
435 selectionHighlighter.clearSelection();
440 * Respond to a change of the base hovered over in the Varna viewer
443 public void onHoverChanged(ModeleBase previousBase, ModeleBase newBase)
445 RNA rna = vab.getSelectedRNA();
446 ShiftList shift = offsetsInv.get(rna);
447 SequenceI seq = models.get(rna).seq;
448 if (newBase != null && seq != null)
452 int i = shift.shift(newBase.getIndex());
453 // System.err.println("shifted "+(arg1.getIndex())+" to "+i);
454 ssm.mouseOverVamsasSequence(seq, i, this);
458 ssm.mouseOverVamsasSequence(seq, newBase.getIndex(), this);
464 public void onSelectionChanged(BaseList arg0, BaseList arg1, BaseList arg2)
466 // TODO translate selected regions in VARNA to a selection on the
472 * Returns the path to a temporary file containing a representation of the
473 * state of one Varna display
479 public String getStateInfo(RNA rna)
481 return vab.getStateInfo(rna);
484 public AlignmentPanel getAlignmentPanel()
489 public String getViewId()
495 * Returns true if any of the viewer's models (not necessarily the one
496 * currently displayed) is for the given sequence
501 public boolean isListeningFor(SequenceI seq)
503 for (RnaModel model : models.values())
505 if (model.seq == seq)
514 * Returns a value representing the horizontal split divider location
518 public int getDividerLocation()
520 return split == null ? 0 : split.getDividerLocation();
524 * Tidy up as necessary when the viewer panel is closed
526 protected void close()
529 * Deregister as a listener, to release references to this object
533 ssm.removeStructureViewerListener(AppVarna.this, null);
534 ssm.removeSelectionListener(AppVarna.this);
539 * Returns the secondary structure annotation that this viewer displays for
544 public AlignmentAnnotation getAnnotation(SequenceI seq)
546 for (RnaModel model : models.values())
548 if (model.seq == seq)
556 public int getSelectedIndex()
558 return this.vab.getSelectedIndex();
562 * Returns the set of models shown by the viewer
566 public Collection<RnaModel> getModels()
568 return models.values();
572 * Add a model (e.g. loaded from project file)
577 public RNA addModel(RnaModel model, String modelName)
579 if (!model.ann.isValidStruc())
581 throw new IllegalArgumentException("Invalid RNA structure annotation");
585 * opened on request in Jalview session
587 RNA rna = new RNA(modelName);
588 String struc = model.ann.getRNAStruc();
589 struc = replaceOddGaps(struc);
591 String strucseq = model.seq.getSequenceAsString();
594 rna.setRNA(strucseq, struc);
595 } catch (ExceptionUnmatchedClosingParentheses e2)
597 e2.printStackTrace();
598 } catch (ExceptionFileFormatOrSyntax e3)
600 e3.printStackTrace();
605 rna = trimRNA(rna, modelName);
607 models.put(rna, new RnaModel(modelName, model.ann, model.seq, rna,
609 vab.addStructure(rna);
614 * Constructs a shift list that describes the gaps in the sequence
619 protected ShiftList buildOffset(SequenceI seq)
621 // TODO refactor to avoid duplication with trimRNA()
622 // TODO JAL-1789 bugs in use of ShiftList here
623 ShiftList offset = new ShiftList();
625 int sleng = seq.getLength();
626 char[] seqChars = seq.getSequence();
628 for (int i = 0; i < sleng; i++)
630 if (Comparison.isGap(seqChars[i]))
641 offset.addShift(offset.shift(ofstart), ofstart - i);
649 offset.addShift(offset.shift(ofstart), ofstart - sleng);
656 * Set the selected index in the model selection list
658 * @param selectedIndex
660 public void setInitialSelection(final int selectedIndex)
663 * empirically it needs a second for Varna/AWT to finish loading/drawing
664 * models for this to work; SwingUtilities.invokeLater _not_ a solution;
665 * explanation and/or better solution welcome!
672 } catch (InterruptedException e)
677 vab.setSelectedIndex(selectedIndex);
682 * Add a model with associated Varna session file
687 public RNA addModelSession(RnaModel model, String modelName,
690 if (!model.ann.isValidStruc())
692 throw new IllegalArgumentException("Invalid RNA structure annotation");
697 FullBackup fromSession = vab.vp.loadSession(sessionFile);
698 vab.addStructure(fromSession.rna, fromSession.config);
699 RNA rna = fromSession.rna;
700 // copy the model, but now including the RNA object
701 RnaModel newModel = new RnaModel(model.title, model.ann, model.seq,
705 registerOffset(rna, buildOffset(model.seq));
707 models.put(rna, newModel);
708 // capture rna selection state when saved
709 selectionHighlighter = new VarnaHighlighter(rna);
710 return fromSession.rna;
711 } catch (ExceptionLoadingFailed e)
714 .println("Error restoring Varna session: " + e.getMessage());
721 * Replace everything except RNA secondary structure characters with a period
726 public static String replaceOddGaps(String s)
733 // this is measured to be 10 times faster than a regex replace
734 boolean changed = false;
735 byte[] bytes = s.getBytes();
736 for (int i = 0; i < bytes.length; i++)
739 // todo check for ((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')) if
741 for (int j = 0; !ok && (j < PAIRS.length); j++)
743 if (bytes[i] == PAIRS[j])
754 return changed ? new String(bytes) : s;