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[] { '(', ')', '[', ']', '{',
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",
184 new String[] { theTitle });
187 String gappedTitle = sname + " (with gaps)";
188 RnaModel gappedModel = new RnaModel(gappedTitle, aa, seq, null, true);
189 addModel(gappedModel, gappedTitle);
191 String trimmedTitle = "trimmed " + sname;
192 RnaModel trimmedModel = new RnaModel(trimmedTitle, aa, seq, null, false);
193 addModel(trimmedModel, trimmedTitle);
194 vab.setSelectedIndex(0);
198 * Constructor that links the viewer to a parent panel (but has no structures
199 * yet - use addModel to add them)
203 protected AppVarna(AlignmentPanel ap)
206 this.viewId = System.currentTimeMillis() + "." + this.hashCode();
207 vab = new AppVarnaBinding();
210 this.ssm = ap.getStructureSelectionManager();
211 ssm.addStructureViewerListener(this);
212 ssm.addSelectionListener(this);
213 addInternalFrameListener(new InternalFrameAdapter()
216 public void internalFrameClosed(InternalFrameEvent evt)
224 * Constructor given viewer data read from a saved project file
228 * the (or a) parent alignment panel
230 public AppVarna(RnaViewerModel model, AlignmentPanel ap)
233 setTitle(model.title);
234 this.viewId = model.viewId;
235 setBounds(model.x, model.y, model.width, model.height);
236 this.split.setDividerLocation(model.dividerLocation);
240 * Constructs a split pane with an empty selection list and display panel, and
241 * adds it to the desktop
243 public void initVarna()
245 VARNAPanel varnaPanel = vab.get_varnaPanel();
246 setBackground(Color.white);
247 split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true,
248 vab.getListPanel(), varnaPanel);
249 getContentPane().setLayout(new BorderLayout());
250 getContentPane().add(split, BorderLayout.CENTER);
252 varnaPanel.addSelectionListener(this);
253 jalview.gui.Desktop.addInternalFrame(this, "", getBounds().width,
260 * Constructs a new RNA model from the given one, without gaps. Also
261 * calculates and saves a 'shift list'
267 public RNA trimRNA(RNA rna, String name)
269 ShiftList offset = new ShiftList();
271 RNA rnaTrim = new RNA(name);
274 String structDBN = rna.getStructDBN(true);
275 rnaTrim.setRNA(rna.getSeq(), replaceOddGaps(structDBN));
276 } catch (ExceptionUnmatchedClosingParentheses e2)
278 e2.printStackTrace();
279 } catch (ExceptionFileFormatOrSyntax e3)
281 e3.printStackTrace();
284 String seq = rnaTrim.getSeq();
285 StringBuilder struc = new StringBuilder(256);
286 struc.append(rnaTrim.getStructDBN(true));
288 int sleng = seq.length();
290 for (int i = 0; i < sleng; i++)
292 if (Comparison.isGap(seq.charAt(i)))
299 * mark base or base & pair in the structure with *
301 if (!rnaTrim.findPair(i).isEmpty())
303 int m = rnaTrim.findPair(i).get(1);
304 int l = rnaTrim.findPair(i).get(0);
306 struc.replace(m, m + 1, "*");
307 struc.replace(l, l + 1, "*");
311 struc.replace(i, i + 1, "*");
318 offset.addShift(offset.shift(ofstart), ofstart - i);
326 offset.addShift(offset.shift(ofstart), ofstart - sleng);
331 * remove the marked gaps from the structure
333 String newStruc = struc.toString().replace("*", "");
336 * remove gaps from the sequence
338 String newSeq = AlignSeq.extractGaps(Comparison.GapChars, seq);
342 rnaTrim.setRNA(newSeq, newStruc);
343 registerOffset(rnaTrim, offset);
344 } catch (ExceptionUnmatchedClosingParentheses e)
347 } catch (ExceptionFileFormatOrSyntax e)
355 * Save the sequence to structure mapping, and also its inverse.
360 private void registerOffset(RNA rnaTrim, ShiftList offset)
362 offsets.put(rnaTrim, offset);
363 offsetsInv.put(rnaTrim, offset.getInverse());
366 public void showPanel(boolean show)
368 this.setVisible(show);
372 * If a mouseOver event from the AlignmentPanel is noticed the currently
373 * selected RNA in the VARNA window is highlighted at the specific position.
374 * To be able to remove it before the next highlight it is saved in
379 * the aligned sequence position (base 0)
381 * the dataset sequence position (base 1)
384 public void mouseOverSequence(SequenceI sequence, final int index,
387 RNA rna = vab.getSelectedRNA();
392 RnaModel rnaModel = models.get(rna);
393 if (rnaModel.seq == sequence)
395 int highlightPos = rnaModel.gapped ? index : position - 1;
396 mouseOverHighlighter.highlightRegion(rna, highlightPos, highlightPos);
397 vab.updateSelectedRNA(rna);
402 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
403 SelectionSource source)
407 // ignore events from anything but our parent alignpanel
408 // TODO - reuse many-one panel-view system in jmol viewer
411 RNA rna = vab.getSelectedRNA();
416 if (seqsel != null && seqsel.getSize() > 0)
418 int start = seqsel.getStartRes(), end = seqsel.getEndRes();
419 ShiftList shift = offsets.get(rna);
422 start = shift.shift(start);
423 end = shift.shift(end);
425 selectionHighlighter.highlightRegion(rna, start, end);
426 selectionHighlighter.getLastHighlight().setOutlineColor(
427 seqsel.getOutlineColour());
428 // TODO - translate column markings to positions on structure if present.
429 vab.updateSelectedRNA(rna);
433 selectionHighlighter.clearSelection();
438 * Respond to a change of the base hovered over in the Varna viewer
441 public void onHoverChanged(ModeleBase previousBase, ModeleBase newBase)
443 RNA rna = vab.getSelectedRNA();
444 ShiftList shift = offsetsInv.get(rna);
445 SequenceI seq = models.get(rna).seq;
446 if (newBase != null && seq != null)
450 int i = shift.shift(newBase.getIndex());
451 // System.err.println("shifted "+(arg1.getIndex())+" to "+i);
452 ssm.mouseOverVamsasSequence(seq, i, this);
456 ssm.mouseOverVamsasSequence(seq, newBase.getIndex(), this);
462 public void onSelectionChanged(BaseList arg0, BaseList arg1, BaseList arg2)
464 // TODO translate selected regions in VARNA to a selection on the
470 * Returns the path to a temporary file containing a representation of the
471 * state of one Varna display
477 public String getStateInfo(RNA rna)
479 return vab.getStateInfo(rna);
482 public AlignmentPanel getAlignmentPanel()
487 public String getViewId()
493 * Returns true if any of the viewer's models (not necessarily the one
494 * currently displayed) is for the given sequence
499 public boolean isListeningFor(SequenceI seq)
501 for (RnaModel model : models.values())
503 if (model.seq == seq)
512 * Returns a value representing the horizontal split divider location
516 public int getDividerLocation()
518 return split == null ? 0 : split.getDividerLocation();
522 * Tidy up as necessary when the viewer panel is closed
524 protected void close()
527 * Deregister as a listener, to release references to this object
531 ssm.removeStructureViewerListener(AppVarna.this, null);
532 ssm.removeSelectionListener(AppVarna.this);
537 * Returns the secondary structure annotation that this viewer displays for
542 public AlignmentAnnotation getAnnotation(SequenceI seq)
544 for (RnaModel model : models.values())
546 if (model.seq == seq)
554 public int getSelectedIndex()
556 return this.vab.getSelectedIndex();
560 * Returns the set of models shown by the viewer
564 public Collection<RnaModel> getModels()
566 return models.values();
570 * Add a model (e.g. loaded from project file)
575 public RNA addModel(RnaModel model, String modelName)
577 if (!model.ann.isValidStruc())
579 throw new IllegalArgumentException("Invalid RNA structure annotation");
583 * opened on request in Jalview session
585 RNA rna = new RNA(modelName);
586 String struc = model.ann.getRNAStruc();
587 struc = replaceOddGaps(struc);
589 String strucseq = model.seq.getSequenceAsString();
592 rna.setRNA(strucseq, struc);
593 } catch (ExceptionUnmatchedClosingParentheses e2)
595 e2.printStackTrace();
596 } catch (ExceptionFileFormatOrSyntax e3)
598 e3.printStackTrace();
603 rna = trimRNA(rna, modelName);
605 models.put(rna, new RnaModel(modelName, model.ann, model.seq, rna,
607 vab.addStructure(rna);
612 * Constructs a shift list that describes the gaps in the sequence
617 protected ShiftList buildOffset(SequenceI seq)
619 // TODO refactor to avoid duplication with trimRNA()
620 // TODO JAL-1789 bugs in use of ShiftList here
621 ShiftList offset = new ShiftList();
623 int sleng = seq.getLength();
624 char[] seqChars = seq.getSequence();
626 for (int i = 0; i < sleng; i++)
628 if (Comparison.isGap(seqChars[i]))
639 offset.addShift(offset.shift(ofstart), ofstart - i);
647 offset.addShift(offset.shift(ofstart), ofstart - sleng);
654 * Set the selected index in the model selection list
656 * @param selectedIndex
658 public void setInitialSelection(final int selectedIndex)
661 * empirically it needs a second for Varna/AWT to finish loading/drawing
662 * models for this to work; SwingUtilities.invokeLater _not_ a solution;
663 * explanation and/or better solution welcome!
670 } catch (InterruptedException e)
675 vab.setSelectedIndex(selectedIndex);
679 * Add a model with associated Varna session file
684 public RNA addModelSession(RnaModel model, String modelName,
687 if (!model.ann.isValidStruc())
689 throw new IllegalArgumentException("Invalid RNA structure annotation");
694 FullBackup fromSession = vab.vp.loadSession(sessionFile);
695 vab.addStructure(fromSession.rna, fromSession.config);
696 RNA rna = fromSession.rna;
697 // copy the model, but now including the RNA object
698 RnaModel newModel = new RnaModel(model.title, model.ann, model.seq,
702 registerOffset(rna, buildOffset(model.seq));
704 models.put(rna, newModel);
705 // capture rna selection state when saved
706 selectionHighlighter = new VarnaHighlighter(rna);
707 return fromSession.rna;
708 } catch (ExceptionLoadingFailed e)
711 .println("Error restoring Varna session: " + e.getMessage());
717 * Replace everything except RNA secondary structure characters with a period
722 public static String replaceOddGaps(String s)
729 // this is measured to be 10 times faster than a regex replace
730 boolean changed = false;
731 byte[] bytes = s.getBytes();
732 for (int i = 0; i < bytes.length; i++)
735 // todo check for ((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')) if
737 for (int j = 0; !ok && (j < PAIRS.length); j++)
739 if (bytes[i] == PAIRS[j])
750 return changed ? new String(bytes) : s;