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);
123 public void highlightRegion(RNA rna, int start, int end)
125 clearLastSelection();
126 HighlightRegionAnnotation highlight = new HighlightRegionAnnotation(
127 rna.getBasesBetween(start, end));
128 rna.addHighlightRegion(highlight);
129 _lastHighlight = highlight;
130 _lastRNAhighlighted = rna;
133 public HighlightRegionAnnotation getLastHighlight()
135 return _lastHighlight;
139 * Clears all structure selection and refreshes the display
141 public void clearSelection()
143 if (_lastRNAhighlighted != null)
145 _lastRNAhighlighted.getHighlightRegion().clear();
146 vab.updateSelectedRNA(_lastRNAhighlighted);
147 _lastRNAhighlighted = null;
148 _lastHighlight = null;
153 * Clear the last structure selection
155 public void clearLastSelection()
157 if (_lastRNAhighlighted != null)
159 _lastRNAhighlighted.removeHighlightRegion(_lastHighlight);
160 _lastRNAhighlighted = null;
161 _lastHighlight = null;
172 * the annotation with the secondary structure string
174 * the AlignmentPanel creating this object
176 public AppVarna(SequenceI seq, AlignmentAnnotation aa, AlignmentPanel ap)
180 String sname = aa.sequenceRef == null
181 ? "secondary structure (alignment)"
182 : seq.getName() + " structure";
183 String theTitle = sname
184 + (aa.sequenceRef == null ? " trimmed to " + seq.getName()
186 theTitle = MessageManager.formatMessage("label.varna_params",
191 String gappedTitle = sname + " (with gaps)";
192 RnaModel gappedModel = new RnaModel(gappedTitle, aa, seq, null, true);
193 addModel(gappedModel, gappedTitle);
195 String trimmedTitle = "trimmed " + sname;
196 RnaModel trimmedModel = new RnaModel(trimmedTitle, aa, seq, null,
198 addModel(trimmedModel, trimmedTitle);
199 vab.setSelectedIndex(0);
203 * Constructor that links the viewer to a parent panel (but has no structures
204 * yet - use addModel to add them)
208 protected AppVarna(AlignmentPanel ap)
211 this.viewId = System.currentTimeMillis() + "." + this.hashCode();
212 vab = new AppVarnaBinding();
215 this.ssm = ap.getStructureSelectionManager();
216 ssm.addStructureViewerListener(this);
217 ssm.addSelectionListener(this);
218 addInternalFrameListener(new InternalFrameAdapter()
221 public void internalFrameClosed(InternalFrameEvent evt)
229 * Constructor given viewer data read from a saved project file
233 * the (or a) parent alignment panel
235 public AppVarna(RnaViewerModel model, AlignmentPanel ap)
238 setTitle(model.title);
239 this.viewId = model.viewId;
240 setBounds(model.x, model.y, model.width, model.height);
241 this.split.setDividerLocation(model.dividerLocation);
245 * Constructs a split pane with an empty selection list and display panel, and
246 * adds it to the desktop
248 public void initVarna()
250 VARNAPanel varnaPanel = vab.get_varnaPanel();
251 setBackground(Color.white);
252 split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true,
253 vab.getListPanel(), varnaPanel);
254 getContentPane().setLayout(new BorderLayout());
255 getContentPane().add(split, BorderLayout.CENTER);
257 varnaPanel.addSelectionListener(this);
258 jalview.gui.Desktop.addInternalFrame(this, "", getBounds().width,
265 * Constructs a new RNA model from the given one, without gaps. Also
266 * calculates and saves a 'shift list'
272 public RNA trimRNA(RNA rna, String name)
274 ShiftList offset = new ShiftList();
276 RNA rnaTrim = new RNA(name);
279 String structDBN = rna.getStructDBN(true);
280 rnaTrim.setRNA(rna.getSeq(), replaceOddGaps(structDBN));
281 } catch (ExceptionUnmatchedClosingParentheses e2)
283 e2.printStackTrace();
284 } catch (ExceptionFileFormatOrSyntax e3)
286 e3.printStackTrace();
289 String seq = rnaTrim.getSeq();
290 StringBuilder struc = new StringBuilder(256);
291 struc.append(rnaTrim.getStructDBN(true));
293 int sleng = seq.length();
295 for (int i = 0; i < sleng; i++)
297 if (Comparison.isGap(seq.charAt(i)))
304 * mark base or base & pair in the structure with *
306 if (!rnaTrim.findPair(i).isEmpty())
308 int m = rnaTrim.findPair(i).get(1);
309 int l = rnaTrim.findPair(i).get(0);
311 struc.replace(m, m + 1, "*");
312 struc.replace(l, l + 1, "*");
316 struc.replace(i, i + 1, "*");
323 offset.addShift(offset.shift(ofstart), ofstart - i);
331 offset.addShift(offset.shift(ofstart), ofstart - sleng);
336 * remove the marked gaps from the structure
338 String newStruc = struc.toString().replace("*", "");
341 * remove gaps from the sequence
343 String newSeq = AlignSeq.extractGaps(Comparison.GapChars, seq);
347 rnaTrim.setRNA(newSeq, newStruc);
348 registerOffset(rnaTrim, offset);
349 } catch (ExceptionUnmatchedClosingParentheses e)
352 } catch (ExceptionFileFormatOrSyntax e)
360 * Save the sequence to structure mapping, and also its inverse.
365 private void registerOffset(RNA rnaTrim, ShiftList offset)
367 offsets.put(rnaTrim, offset);
368 offsetsInv.put(rnaTrim, offset.getInverse());
371 public void showPanel(boolean show)
373 this.setVisible(show);
377 * If a mouseOver event from the AlignmentPanel is noticed the currently
378 * selected RNA in the VARNA window is highlighted at the specific position.
379 * To be able to remove it before the next highlight it is saved in
384 * the aligned sequence position (base 0)
386 * the dataset sequence position (base 1)
389 public void mouseOverSequence(SequenceI sequence, final int index,
392 RNA rna = vab.getSelectedRNA();
397 RnaModel rnaModel = models.get(rna);
398 if (rnaModel.seq == sequence)
400 int highlightPos = rnaModel.gapped ? index : position - 1;
401 mouseOverHighlighter.highlightRegion(rna, highlightPos, highlightPos);
402 vab.updateSelectedRNA(rna);
407 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
408 HiddenColumns hidden, SelectionSource source)
412 // ignore events from anything but our parent alignpanel
413 // TODO - reuse many-one panel-view system in jmol viewer
416 RNA rna = vab.getSelectedRNA();
421 if (seqsel != null && seqsel.getSize() > 0)
423 int start = seqsel.getStartRes(), end = seqsel.getEndRes();
424 ShiftList shift = offsets.get(rna);
427 start = shift.shift(start);
428 end = shift.shift(end);
430 selectionHighlighter.highlightRegion(rna, start, end);
431 selectionHighlighter.getLastHighlight()
432 .setOutlineColor(seqsel.getOutlineColour());
433 // TODO - translate column markings to positions on structure if present.
434 vab.updateSelectedRNA(rna);
438 selectionHighlighter.clearSelection();
443 * Respond to a change of the base hovered over in the Varna viewer
446 public void onHoverChanged(ModeleBase previousBase, ModeleBase newBase)
448 RNA rna = vab.getSelectedRNA();
449 ShiftList shift = offsetsInv.get(rna);
450 SequenceI seq = models.get(rna).seq;
451 if (newBase != null && seq != null)
455 int i = shift.shift(newBase.getIndex());
456 // System.err.println("shifted "+(arg1.getIndex())+" to "+i);
457 ssm.mouseOverVamsasSequence(seq, i, this);
461 ssm.mouseOverVamsasSequence(seq, newBase.getIndex(), this);
467 public void onSelectionChanged(BaseList arg0, BaseList arg1,
470 // TODO translate selected regions in VARNA to a selection on the
476 * Returns the path to a temporary file containing a representation of the
477 * state of one Varna display
483 public String getStateInfo(RNA rna)
485 return vab.getStateInfo(rna);
488 public AlignmentPanel getAlignmentPanel()
493 public String getViewId()
499 * Returns true if any of the viewer's models (not necessarily the one
500 * currently displayed) is for the given sequence
505 public boolean isListeningFor(SequenceI seq)
507 for (RnaModel model : models.values())
509 if (model.seq == seq)
518 * Returns a value representing the horizontal split divider location
522 public int getDividerLocation()
524 return split == null ? 0 : split.getDividerLocation();
528 * Tidy up as necessary when the viewer panel is closed
530 protected void close()
533 * Deregister as a listener, to release references to this object
537 ssm.removeStructureViewerListener(AppVarna.this, null);
538 ssm.removeSelectionListener(AppVarna.this);
543 * Returns the secondary structure annotation that this viewer displays for
548 public AlignmentAnnotation getAnnotation(SequenceI seq)
550 for (RnaModel model : models.values())
552 if (model.seq == seq)
560 public int getSelectedIndex()
562 return this.vab.getSelectedIndex();
566 * Returns the set of models shown by the viewer
570 public Collection<RnaModel> getModels()
572 return models.values();
576 * Add a model (e.g. loaded from project file)
581 public RNA addModel(RnaModel model, String modelName)
583 if (!model.ann.isValidStruc())
585 throw new IllegalArgumentException(
586 "Invalid RNA structure annotation");
590 * opened on request in Jalview session
592 RNA rna = new RNA(modelName);
593 String struc = model.ann.getRNAStruc();
594 struc = replaceOddGaps(struc);
596 String strucseq = model.seq.getSequenceAsString();
599 rna.setRNA(strucseq, struc);
600 } catch (ExceptionUnmatchedClosingParentheses e2)
602 e2.printStackTrace();
603 } catch (ExceptionFileFormatOrSyntax e3)
605 e3.printStackTrace();
610 rna = trimRNA(rna, modelName);
612 models.put(rna, new RnaModel(modelName, model.ann, model.seq, rna,
614 vab.addStructure(rna);
619 * Constructs a shift list that describes the gaps in the sequence
624 protected ShiftList buildOffset(SequenceI seq)
626 // TODO refactor to avoid duplication with trimRNA()
627 // TODO JAL-1789 bugs in use of ShiftList here
628 ShiftList offset = new ShiftList();
630 int sleng = seq.getLength();
632 for (int i = 0; i < sleng; i++)
634 if (Comparison.isGap(seq.getCharAt(i)))
645 offset.addShift(offset.shift(ofstart), ofstart - i);
653 offset.addShift(offset.shift(ofstart), ofstart - sleng);
660 * Set the selected index in the model selection list
662 * @param selectedIndex
664 public void setInitialSelection(final int selectedIndex)
667 * empirically it needs a second for Varna/AWT to finish loading/drawing
668 * models for this to work; SwingUtilities.invokeLater _not_ a solution;
669 * explanation and/or better solution welcome!
676 } catch (InterruptedException e)
681 vab.setSelectedIndex(selectedIndex);
685 * Add a model with associated Varna session file
690 public RNA addModelSession(RnaModel model, String modelName,
693 if (!model.ann.isValidStruc())
695 throw new IllegalArgumentException(
696 "Invalid RNA structure annotation");
701 FullBackup fromSession = vab.vp.loadSession(sessionFile);
702 vab.addStructure(fromSession.rna, fromSession.config);
703 RNA rna = fromSession.rna;
704 // copy the model, but now including the RNA object
705 RnaModel newModel = new RnaModel(model.title, model.ann, model.seq,
709 registerOffset(rna, buildOffset(model.seq));
711 models.put(rna, newModel);
712 // capture rna selection state when saved
713 selectionHighlighter = new VarnaHighlighter(rna);
714 return fromSession.rna;
715 } catch (ExceptionLoadingFailed e)
718 .println("Error restoring Varna session: " + e.getMessage());
724 * Replace everything except RNA secondary structure characters with a period
729 public static String replaceOddGaps(String s)
736 // this is measured to be 10 times faster than a regex replace
737 boolean changed = false;
738 byte[] bytes = s.getBytes();
739 for (int i = 0; i < bytes.length; i++)
742 // todo check for ((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')) if
744 for (int j = 0; !ok && (j < PAIRS.length); j++)
746 if (bytes[i] == PAIRS[j])
757 return changed ? new String(bytes) : s;