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.HiddenColumns;
27 import jalview.datamodel.RnaViewerModel;
28 import jalview.datamodel.SequenceGroup;
29 import jalview.datamodel.SequenceI;
30 import jalview.ext.varna.RnaModel;
31 import jalview.structure.SecondaryStructureListener;
32 import jalview.structure.SelectionListener;
33 import jalview.structure.SelectionSource;
34 import jalview.structure.StructureSelectionManager;
35 import jalview.structure.VamsasSource;
36 import jalview.util.Comparison;
37 import jalview.util.MessageManager;
38 import jalview.util.ShiftList;
40 import java.awt.BorderLayout;
41 import java.awt.Color;
42 import java.util.Collection;
43 import java.util.Hashtable;
44 import java.util.LinkedHashMap;
45 import java.util.List;
48 import javax.swing.JInternalFrame;
49 import javax.swing.JSplitPane;
50 import javax.swing.event.InternalFrameAdapter;
51 import javax.swing.event.InternalFrameEvent;
53 import fr.orsay.lri.varna.VARNAPanel;
54 import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
55 import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
56 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
57 import fr.orsay.lri.varna.interfaces.InterfaceVARNASelectionListener;
58 import fr.orsay.lri.varna.models.BaseList;
59 import fr.orsay.lri.varna.models.FullBackup;
60 import fr.orsay.lri.varna.models.annotations.HighlightRegionAnnotation;
61 import fr.orsay.lri.varna.models.rna.ModeleBase;
62 import fr.orsay.lri.varna.models.rna.RNA;
64 public class AppVarna extends JInternalFrame
65 implements SelectionListener, SecondaryStructureListener,
66 InterfaceVARNASelectionListener, VamsasSource
68 private static final byte[] PAIRS = new byte[] { '(', ')', '[', ']', '{',
71 private AppVarnaBinding vab;
73 private AlignmentPanel ap;
75 private String viewId;
77 private StructureSelectionManager ssm;
80 * Lookup for sequence and annotation mapped to each RNA in the viewer. Using
81 * a linked hashmap means that order is preserved when saved to the project.
83 private Map<RNA, RnaModel> models = new LinkedHashMap<RNA, RnaModel>();
85 private Map<RNA, ShiftList> offsets = new Hashtable<RNA, ShiftList>();
87 private Map<RNA, ShiftList> offsetsInv = new Hashtable<RNA, ShiftList>();
89 private JSplitPane split;
91 private VarnaHighlighter mouseOverHighlighter = new VarnaHighlighter();
93 private VarnaHighlighter selectionHighlighter = new VarnaHighlighter();
95 private class VarnaHighlighter
97 private HighlightRegionAnnotation _lastHighlight;
99 private RNA _lastRNAhighlighted = null;
101 public VarnaHighlighter()
107 * Constructor when restoring from Varna session, including any highlight
112 public VarnaHighlighter(RNA rna)
114 // TODO nice try but doesn't work; do we need a highlighter per model?
115 _lastRNAhighlighted = rna;
116 List<HighlightRegionAnnotation> highlights = rna.getHighlightRegion();
117 if (highlights != null && !highlights.isEmpty())
119 _lastHighlight = highlights.get(0);
124 * highlight a region from start to end (inclusive) on rna
128 * - first base pair index (from 0)
130 * - last base pair index (from 0)
132 public void highlightRegion(RNA rna, int start, int end)
134 clearLastSelection();
135 HighlightRegionAnnotation highlight = new HighlightRegionAnnotation(
136 rna.getBasesBetween(start, end));
137 rna.addHighlightRegion(highlight);
138 _lastHighlight = highlight;
139 _lastRNAhighlighted = rna;
142 public HighlightRegionAnnotation getLastHighlight()
144 return _lastHighlight;
148 * Clears all structure selection and refreshes the display
150 public void clearSelection()
152 if (_lastRNAhighlighted != null)
154 _lastRNAhighlighted.getHighlightRegion().clear();
155 vab.updateSelectedRNA(_lastRNAhighlighted);
156 _lastRNAhighlighted = null;
157 _lastHighlight = null;
162 * Clear the last structure selection
164 public void clearLastSelection()
166 if (_lastRNAhighlighted != null)
168 _lastRNAhighlighted.removeHighlightRegion(_lastHighlight);
169 _lastRNAhighlighted = null;
170 _lastHighlight = null;
181 * the annotation with the secondary structure string
183 * the AlignmentPanel creating this object
185 public AppVarna(SequenceI seq, AlignmentAnnotation aa, AlignmentPanel ap)
189 String sname = aa.sequenceRef == null
190 ? "secondary structure (alignment)"
191 : seq.getName() + " structure";
192 String theTitle = sname
193 + (aa.sequenceRef == null ? " trimmed to " + seq.getName()
195 theTitle = MessageManager.formatMessage("label.varna_params",
200 String gappedTitle = sname + " (with gaps)";
201 RnaModel gappedModel = new RnaModel(gappedTitle, aa, seq, null, true);
202 addModel(gappedModel, gappedTitle);
204 String trimmedTitle = "trimmed " + sname;
205 RnaModel trimmedModel = new RnaModel(trimmedTitle, aa, seq, null,
207 addModel(trimmedModel, trimmedTitle);
208 vab.setSelectedIndex(0);
212 * Constructor that links the viewer to a parent panel (but has no structures
213 * yet - use addModel to add them)
217 protected AppVarna(AlignmentPanel ap)
220 this.viewId = System.currentTimeMillis() + "." + this.hashCode();
221 vab = new AppVarnaBinding();
224 this.ssm = ap.getStructureSelectionManager();
225 ssm.addStructureViewerListener(this);
226 ssm.addSelectionListener(this);
227 addInternalFrameListener(new InternalFrameAdapter()
230 public void internalFrameClosed(InternalFrameEvent evt)
238 * Constructor given viewer data read from a saved project file
242 * the (or a) parent alignment panel
244 public AppVarna(RnaViewerModel model, AlignmentPanel ap)
247 setTitle(model.title);
248 this.viewId = model.viewId;
249 setBounds(model.x, model.y, model.width, model.height);
250 this.split.setDividerLocation(model.dividerLocation);
254 * Constructs a split pane with an empty selection list and display panel, and
255 * adds it to the desktop
257 public void initVarna()
259 VARNAPanel varnaPanel = vab.get_varnaPanel();
260 setBackground(Color.white);
261 split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true,
262 vab.getListPanel(), varnaPanel);
263 getContentPane().setLayout(new BorderLayout());
264 getContentPane().add(split, BorderLayout.CENTER);
266 varnaPanel.addSelectionListener(this);
267 jalview.gui.Desktop.addInternalFrame(this, "", getBounds().width,
274 * Constructs a new RNA model from the given one, without gaps. Also
275 * calculates and saves a 'shift list'
281 public RNA trimRNA(RNA rna, String name)
283 ShiftList offset = new ShiftList();
285 RNA rnaTrim = new RNA(name);
288 String structDBN = rna.getStructDBN(true);
289 rnaTrim.setRNA(rna.getSeq(), replaceOddGaps(structDBN));
290 } catch (ExceptionUnmatchedClosingParentheses e2)
292 e2.printStackTrace();
293 } catch (ExceptionFileFormatOrSyntax e3)
295 e3.printStackTrace();
298 String seq = rnaTrim.getSeq();
299 StringBuilder struc = new StringBuilder(256);
300 struc.append(rnaTrim.getStructDBN(true));
302 int sleng = seq.length();
304 for (int i = 0; i < sleng; i++)
306 if (Comparison.isGap(seq.charAt(i)))
313 * mark base or base & pair in the structure with *
315 if (!rnaTrim.findPair(i).isEmpty())
317 int m = rnaTrim.findPair(i).get(1);
318 int l = rnaTrim.findPair(i).get(0);
320 struc.replace(m, m + 1, "*");
321 struc.replace(l, l + 1, "*");
325 struc.replace(i, i + 1, "*");
332 offset.addShift(offset.shift(ofstart), ofstart - i);
340 offset.addShift(offset.shift(ofstart), ofstart - sleng);
345 * remove the marked gaps from the structure
347 String newStruc = struc.toString().replace("*", "");
350 * remove gaps from the sequence
352 String newSeq = AlignSeq.extractGaps(Comparison.GapChars, seq);
356 rnaTrim.setRNA(newSeq, newStruc);
357 registerOffset(rnaTrim, offset);
358 } catch (ExceptionUnmatchedClosingParentheses e)
361 } catch (ExceptionFileFormatOrSyntax e)
369 * Save the sequence to structure mapping, and also its inverse.
374 private void registerOffset(RNA rnaTrim, ShiftList offset)
376 offsets.put(rnaTrim, offset);
377 offsetsInv.put(rnaTrim, offset.getInverse());
380 public void showPanel(boolean show)
382 this.setVisible(show);
386 * If a mouseOver event from the AlignmentPanel is noticed the currently
387 * selected RNA in the VARNA window is highlighted at the specific position.
388 * To be able to remove it before the next highlight it is saved in
393 * the aligned sequence position (base 0)
395 * the dataset sequence position (base 1)
398 public void mouseOverSequence(SequenceI sequence, final int index,
401 RNA rna = vab.getSelectedRNA();
406 RnaModel rnaModel = models.get(rna);
407 if (rnaModel.seq == sequence)
409 int highlightPos = rnaModel.gapped ? index
410 : position - sequence.getStart();
411 mouseOverHighlighter.highlightRegion(rna, highlightPos, highlightPos);
412 vab.updateSelectedRNA(rna);
417 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
418 HiddenColumns hidden, SelectionSource source)
422 // ignore events from anything but our parent alignpanel
423 // TODO - reuse many-one panel-view system in jmol viewer
426 RNA rna = vab.getSelectedRNA();
431 if (seqsel != null && seqsel.getSize() > 0)
433 int start = seqsel.getStartRes(), end = seqsel.getEndRes();
434 ShiftList shift = offsets.get(rna);
437 start = shift.shift(start);
438 end = shift.shift(end);
440 selectionHighlighter.highlightRegion(rna, start, end);
441 selectionHighlighter.getLastHighlight()
442 .setOutlineColor(seqsel.getOutlineColour());
443 // TODO - translate column markings to positions on structure if present.
444 vab.updateSelectedRNA(rna);
448 selectionHighlighter.clearSelection();
453 * Respond to a change of the base hovered over in the Varna viewer
456 public void onHoverChanged(ModeleBase previousBase, ModeleBase newBase)
458 RNA rna = vab.getSelectedRNA();
459 ShiftList shift = offsetsInv.get(rna);
460 SequenceI seq = models.get(rna).seq;
461 if (newBase != null && seq != null)
465 int i = shift.shift(newBase.getIndex());
466 // System.err.println("shifted "+(arg1.getIndex())+" to "+i);
467 ssm.mouseOverVamsasSequence(seq, i, this);
471 ssm.mouseOverVamsasSequence(seq, newBase.getIndex(), this);
477 public void onSelectionChanged(BaseList arg0, BaseList arg1,
480 // TODO translate selected regions in VARNA to a selection on the
486 * Returns the path to a temporary file containing a representation of the
487 * state of one Varna display
493 public String getStateInfo(RNA rna)
495 return vab.getStateInfo(rna);
498 public AlignmentPanel getAlignmentPanel()
503 public String getViewId()
509 * Returns true if any of the viewer's models (not necessarily the one
510 * currently displayed) is for the given sequence
515 public boolean isListeningFor(SequenceI seq)
517 for (RnaModel model : models.values())
519 if (model.seq == seq)
528 * Returns a value representing the horizontal split divider location
532 public int getDividerLocation()
534 return split == null ? 0 : split.getDividerLocation();
538 * Tidy up as necessary when the viewer panel is closed
540 protected void close()
543 * Deregister as a listener, to release references to this object
547 ssm.removeStructureViewerListener(AppVarna.this, null);
548 ssm.removeSelectionListener(AppVarna.this);
553 * Returns the secondary structure annotation that this viewer displays for
558 public AlignmentAnnotation getAnnotation(SequenceI seq)
560 for (RnaModel model : models.values())
562 if (model.seq == seq)
570 public int getSelectedIndex()
572 return this.vab.getSelectedIndex();
576 * Returns the set of models shown by the viewer
580 public Collection<RnaModel> getModels()
582 return models.values();
586 * Add a model (e.g. loaded from project file)
591 public RNA addModel(RnaModel model, String modelName)
593 if (!model.ann.isValidStruc())
595 throw new IllegalArgumentException(
596 "Invalid RNA structure annotation");
600 * opened on request in Jalview session
602 RNA rna = new RNA(modelName);
603 String struc = model.ann.getRNAStruc();
604 struc = replaceOddGaps(struc);
606 String strucseq = model.seq.getSequenceAsString();
609 rna.setRNA(strucseq, struc);
610 } catch (ExceptionUnmatchedClosingParentheses e2)
612 e2.printStackTrace();
613 } catch (ExceptionFileFormatOrSyntax e3)
615 e3.printStackTrace();
620 rna = trimRNA(rna, modelName);
622 models.put(rna, new RnaModel(modelName, model.ann, model.seq, rna,
624 vab.addStructure(rna);
629 * Constructs a shift list that describes the gaps in the sequence
634 protected ShiftList buildOffset(SequenceI seq)
636 // TODO refactor to avoid duplication with trimRNA()
637 // TODO JAL-1789 bugs in use of ShiftList here
638 ShiftList offset = new ShiftList();
640 int sleng = seq.getLength();
642 for (int i = 0; i < sleng; i++)
644 if (Comparison.isGap(seq.getCharAt(i)))
655 offset.addShift(offset.shift(ofstart), ofstart - i);
663 offset.addShift(offset.shift(ofstart), ofstart - sleng);
670 * Set the selected index in the model selection list
672 * @param selectedIndex
674 public void setInitialSelection(final int selectedIndex)
677 * empirically it needs a second for Varna/AWT to finish loading/drawing
678 * models for this to work; SwingUtilities.invokeLater _not_ a solution;
679 * explanation and/or better solution welcome!
686 } catch (InterruptedException e)
691 vab.setSelectedIndex(selectedIndex);
695 * Add a model with associated Varna session file
700 public RNA addModelSession(RnaModel model, String modelName,
703 if (!model.ann.isValidStruc())
705 throw new IllegalArgumentException(
706 "Invalid RNA structure annotation");
711 FullBackup fromSession = vab.vp.loadSession(sessionFile);
712 vab.addStructure(fromSession.rna, fromSession.config);
713 RNA rna = fromSession.rna;
714 // copy the model, but now including the RNA object
715 RnaModel newModel = new RnaModel(model.title, model.ann, model.seq,
719 registerOffset(rna, buildOffset(model.seq));
721 models.put(rna, newModel);
722 // capture rna selection state when saved
723 selectionHighlighter = new VarnaHighlighter(rna);
724 return fromSession.rna;
725 } catch (ExceptionLoadingFailed e)
728 .println("Error restoring Varna session: " + e.getMessage());
734 * Replace everything except RNA secondary structure characters with a period
739 public static String replaceOddGaps(String s)
746 // this is measured to be 10 times faster than a regex replace
747 boolean changed = false;
748 byte[] bytes = s.getBytes();
749 for (int i = 0; i < bytes.length; i++)
752 // todo check for ((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')) if
754 for (int j = 0; !ok && (j < PAIRS.length); j++)
756 if (bytes[i] == PAIRS[j])
767 return changed ? new String(bytes) : s;