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 implements SelectionListener,
65 SecondaryStructureListener, InterfaceVARNASelectionListener,
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 ? "secondary structure (alignment)"
181 : seq.getName() + " structure";
182 String theTitle = sname
183 + (aa.sequenceRef == null ? " trimmed to " + seq.getName() : "");
184 theTitle = MessageManager.formatMessage("label.varna_params",
185 new String[] { theTitle });
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);
199 * Constructor that links the viewer to a parent panel (but has no structures
200 * yet - use addModel to add them)
204 protected AppVarna(AlignmentPanel ap)
207 this.viewId = System.currentTimeMillis() + "." + this.hashCode();
208 vab = new AppVarnaBinding();
211 this.ssm = ap.getStructureSelectionManager();
212 ssm.addStructureViewerListener(this);
213 ssm.addSelectionListener(this);
214 addInternalFrameListener(new InternalFrameAdapter()
217 public void internalFrameClosed(InternalFrameEvent evt)
225 * Constructor given viewer data read from a saved project file
229 * the (or a) parent alignment panel
231 public AppVarna(RnaViewerModel model, AlignmentPanel ap)
234 setTitle(model.title);
235 this.viewId = model.viewId;
236 setBounds(model.x, model.y, model.width, model.height);
237 this.split.setDividerLocation(model.dividerLocation);
241 * Constructs a split pane with an empty selection list and display panel, and
242 * adds it to the desktop
244 public void initVarna()
246 VARNAPanel varnaPanel = vab.get_varnaPanel();
247 setBackground(Color.white);
248 split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true,
249 vab.getListPanel(), varnaPanel);
250 getContentPane().setLayout(new BorderLayout());
251 getContentPane().add(split, BorderLayout.CENTER);
253 varnaPanel.addSelectionListener(this);
254 jalview.gui.Desktop.addInternalFrame(this, "", getBounds().width,
261 * Constructs a new RNA model from the given one, without gaps. Also
262 * calculates and saves a 'shift list'
268 public RNA trimRNA(RNA rna, String name)
270 ShiftList offset = new ShiftList();
272 RNA rnaTrim = new RNA(name);
275 String structDBN = rna.getStructDBN(true);
276 rnaTrim.setRNA(rna.getSeq(), replaceOddGaps(structDBN));
277 } catch (ExceptionUnmatchedClosingParentheses e2)
279 e2.printStackTrace();
280 } catch (ExceptionFileFormatOrSyntax e3)
282 e3.printStackTrace();
285 String seq = rnaTrim.getSeq();
286 StringBuilder struc = new StringBuilder(256);
287 struc.append(rnaTrim.getStructDBN(true));
289 int sleng = seq.length();
291 for (int i = 0; i < sleng; i++)
293 if (Comparison.isGap(seq.charAt(i)))
300 * mark base or base & pair in the structure with *
302 if (!rnaTrim.findPair(i).isEmpty())
304 int m = rnaTrim.findPair(i).get(1);
305 int l = rnaTrim.findPair(i).get(0);
307 struc.replace(m, m + 1, "*");
308 struc.replace(l, l + 1, "*");
312 struc.replace(i, i + 1, "*");
319 offset.addShift(offset.shift(ofstart), ofstart - i);
327 offset.addShift(offset.shift(ofstart), ofstart - sleng);
332 * remove the marked gaps from the structure
334 String newStruc = struc.toString().replace("*", "");
337 * remove gaps from the sequence
339 String newSeq = AlignSeq.extractGaps(Comparison.GapChars, seq);
343 rnaTrim.setRNA(newSeq, newStruc);
344 registerOffset(rnaTrim, offset);
345 } catch (ExceptionUnmatchedClosingParentheses e)
348 } catch (ExceptionFileFormatOrSyntax e)
356 * Save the sequence to structure mapping, and also its inverse.
361 private void registerOffset(RNA rnaTrim, ShiftList offset)
363 offsets.put(rnaTrim, offset);
364 offsetsInv.put(rnaTrim, offset.getInverse());
367 public void showPanel(boolean show)
369 this.setVisible(show);
373 * If a mouseOver event from the AlignmentPanel is noticed the currently
374 * selected RNA in the VARNA window is highlighted at the specific position.
375 * To be able to remove it before the next highlight it is saved in
380 * the aligned sequence position (base 0)
382 * the dataset sequence position (base 1)
385 public void mouseOverSequence(SequenceI sequence, final int index,
388 RNA rna = vab.getSelectedRNA();
393 RnaModel rnaModel = models.get(rna);
394 if (rnaModel.seq == sequence)
396 int highlightPos = rnaModel.gapped ? index : position - 1;
397 mouseOverHighlighter.highlightRegion(rna, highlightPos, highlightPos);
398 vab.updateSelectedRNA(rna);
403 public void selection(SequenceGroup seqsel, ColumnSelection colsel,
404 HiddenColumns hidden, SelectionSource source)
408 // ignore events from anything but our parent alignpanel
409 // TODO - reuse many-one panel-view system in jmol viewer
412 RNA rna = vab.getSelectedRNA();
417 if (seqsel != null && seqsel.getSize() > 0)
419 int start = seqsel.getStartRes(), end = seqsel.getEndRes();
420 ShiftList shift = offsets.get(rna);
423 start = shift.shift(start);
424 end = shift.shift(end);
426 selectionHighlighter.highlightRegion(rna, start, end);
427 selectionHighlighter.getLastHighlight().setOutlineColor(
428 seqsel.getOutlineColour());
429 // TODO - translate column markings to positions on structure if present.
430 vab.updateSelectedRNA(rna);
434 selectionHighlighter.clearSelection();
439 * Respond to a change of the base hovered over in the Varna viewer
442 public void onHoverChanged(ModeleBase previousBase, ModeleBase newBase)
444 RNA rna = vab.getSelectedRNA();
445 ShiftList shift = offsetsInv.get(rna);
446 SequenceI seq = models.get(rna).seq;
447 if (newBase != null && seq != null)
451 int i = shift.shift(newBase.getIndex());
452 // System.err.println("shifted "+(arg1.getIndex())+" to "+i);
453 ssm.mouseOverVamsasSequence(seq, i, this);
457 ssm.mouseOverVamsasSequence(seq, newBase.getIndex(), this);
463 public void onSelectionChanged(BaseList arg0, BaseList arg1, BaseList arg2)
465 // TODO translate selected regions in VARNA to a selection on the
471 * Returns the path to a temporary file containing a representation of the
472 * state of one Varna display
478 public String getStateInfo(RNA rna)
480 return vab.getStateInfo(rna);
483 public AlignmentPanel getAlignmentPanel()
488 public String getViewId()
494 * Returns true if any of the viewer's models (not necessarily the one
495 * currently displayed) is for the given sequence
500 public boolean isListeningFor(SequenceI seq)
502 for (RnaModel model : models.values())
504 if (model.seq == seq)
513 * Returns a value representing the horizontal split divider location
517 public int getDividerLocation()
519 return split == null ? 0 : split.getDividerLocation();
523 * Tidy up as necessary when the viewer panel is closed
525 protected void close()
528 * Deregister as a listener, to release references to this object
532 ssm.removeStructureViewerListener(AppVarna.this, null);
533 ssm.removeSelectionListener(AppVarna.this);
538 * Returns the secondary structure annotation that this viewer displays for
543 public AlignmentAnnotation getAnnotation(SequenceI seq)
545 for (RnaModel model : models.values())
547 if (model.seq == seq)
555 public int getSelectedIndex()
557 return this.vab.getSelectedIndex();
561 * Returns the set of models shown by the viewer
565 public Collection<RnaModel> getModels()
567 return models.values();
571 * Add a model (e.g. loaded from project file)
576 public RNA addModel(RnaModel model, String modelName)
578 if (!model.ann.isValidStruc())
580 throw new IllegalArgumentException("Invalid RNA structure annotation");
584 * opened on request in Jalview session
586 RNA rna = new RNA(modelName);
587 String struc = model.ann.getRNAStruc();
588 struc = replaceOddGaps(struc);
590 String strucseq = model.seq.getSequenceAsString();
593 rna.setRNA(strucseq, struc);
594 } catch (ExceptionUnmatchedClosingParentheses e2)
596 e2.printStackTrace();
597 } catch (ExceptionFileFormatOrSyntax e3)
599 e3.printStackTrace();
604 rna = trimRNA(rna, modelName);
606 models.put(rna, new RnaModel(modelName, model.ann, model.seq, rna,
608 vab.addStructure(rna);
613 * Constructs a shift list that describes the gaps in the sequence
618 protected ShiftList buildOffset(SequenceI seq)
620 // TODO refactor to avoid duplication with trimRNA()
621 // TODO JAL-1789 bugs in use of ShiftList here
622 ShiftList offset = new ShiftList();
624 int sleng = seq.getLength();
625 char[] seqChars = seq.getSequence();
627 for (int i = 0; i < sleng; i++)
629 if (Comparison.isGap(seqChars[i]))
640 offset.addShift(offset.shift(ofstart), ofstart - i);
648 offset.addShift(offset.shift(ofstart), ofstart - sleng);
655 * Set the selected index in the model selection list
657 * @param selectedIndex
659 public void setInitialSelection(final int selectedIndex)
662 * empirically it needs a second for Varna/AWT to finish loading/drawing
663 * models for this to work; SwingUtilities.invokeLater _not_ a solution;
664 * explanation and/or better solution welcome!
671 } catch (InterruptedException e)
676 vab.setSelectedIndex(selectedIndex);
680 * Add a model with associated Varna session file
685 public RNA addModelSession(RnaModel model, String modelName,
688 if (!model.ann.isValidStruc())
690 throw new IllegalArgumentException("Invalid RNA structure annotation");
695 FullBackup fromSession = vab.vp.loadSession(sessionFile);
696 vab.addStructure(fromSession.rna, fromSession.config);
697 RNA rna = fromSession.rna;
698 // copy the model, but now including the RNA object
699 RnaModel newModel = new RnaModel(model.title, model.ann, model.seq,
703 registerOffset(rna, buildOffset(model.seq));
705 models.put(rna, newModel);
706 // capture rna selection state when saved
707 selectionHighlighter = new VarnaHighlighter(rna);
708 return fromSession.rna;
709 } catch (ExceptionLoadingFailed e)
712 .println("Error restoring Varna session: " + e.getMessage());
718 * Replace everything except RNA secondary structure characters with a period
723 public static String replaceOddGaps(String s)
730 // this is measured to be 10 times faster than a regex replace
731 boolean changed = false;
732 byte[] bytes = s.getBytes();
733 for (int i = 0; i < bytes.length; i++)
736 // todo check for ((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')) if
738 for (int j = 0; !ok && (j < PAIRS.length); j++)
740 if (bytes[i] == PAIRS[j])
751 return changed ? new String(bytes) : s;