diff -U 3 -H -d -r -N -- original_varna_2.0/VARNA.java src/VARNA.java
--- original_varna_2.0/VARNA.java 2007-11-22 16:05:00.000000000 +0100
+++ src/VARNA.java 2008-06-25 00:51:53.000000000 +0200
@@ -1,255 +1,235 @@
/*
- VARNA is a Java library for quick automated drawings RNA secondary structure
- Copyright (C) 2007 Yann Ponty
+VARNA is a Java library for quick automated drawings RNA secondary structure
+Copyright (C) 2007 Yann Ponty
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
-*/
+You should have received a copy of the GNU General Public License
+along with this program. If not, see .
+ */
-import java.applet.*;
import javax.swing.*;
-import javax.swing.event.ChangeEvent;
-import javax.swing.event.ChangeListener;
-import javax.swing.event.DocumentEvent;
-import javax.swing.event.DocumentListener;
import varna.VARNAPanel;
import java.awt.*;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.awt.event.InputMethodEvent;
-import java.awt.event.InputMethodListener;
-import java.awt.event.KeyEvent;
-import java.awt.event.KeyListener;
-import java.awt.event.MouseEvent;
-import java.awt.event.MouseListener;
-import java.awt.event.WindowEvent;
-import java.awt.event.WindowListener;
+
/**
* An RNA 2d Panel demo applet
* @author Yann Ponty
*
*/
+public class VARNA extends JApplet {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ VARNAPanel _mainSurface = new VARNAPanel();
-public class VARNA extends JApplet {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
+ public VARNA() {
+ super();
+ RNAPanelDemoInit();
+ }
- VARNAPanel _mainSurface = new VARNAPanel();
-
-
- public VARNA()
- {
- super();
- RNAPanelDemoInit();
- }
-
- private void RNAPanelDemoInit()
- {
- _mainSurface.setBackground(_backgroundColor);
- getContentPane().add(_mainSurface,BorderLayout.CENTER);
- setVisible(true);
+ private void RNAPanelDemoInit() {
+ _mainSurface.setBackground(_backgroundColor);
+ getContentPane().add(_mainSurface, BorderLayout.CENTER);
+ setVisible(true);
- }
- // Applet assignable parameters
- private String _algo = "radiate";
- private Color _backgroundColor = Color.white;
- private String _sseq = "CAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIA";
- private String _sstruct = "..(((((...(((((...(((((...(((((.....)))))...))))).....(((((...(((((.....)))))...))))).....)))))...)))))..";
- private int _periodResNum = 5;
- private int _numRows = 1;
- private int _numColumns = 1;
- private String _title ="";
- private int _titleSize = 18;
- private Color _backboneColor = Color.black;
- private Color _bondColor = Color.blue;
- private Color _baseOutlineColor = Color.darkGray;
- private Color _baseInnerColor = new Color(230,230,230);
- private Color _baseNumColor = Color.darkGray;
- private Color _baseNameColor = Color.black;
- private Color _titleColor = Color.black;
+ }
+ // Applet assignable parameters
+ private String _algo = "radiate";
+ private Color _backgroundColor = Color.white;
+ private String _sseq = "CAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIA";
+ private String _sstruct = "..(((((...(((((...(((((...(((((.....)))))...))))).....(((((...(((((.....)))))...))))).....)))))...)))))..";
+ private int _periodResNum = 5;
+ private int _numRows = 1;
+ private int _numColumns = 1;
+ private String _title = "";
+ private int _titleSize = 18;
+ private Color _backboneColor = Color.black;
+ private Color _bondColor = Color.blue;
+ private Color _baseOutlineColor = Color.darkGray;
+ private Color _baseInnerColor = new Color(230, 230, 230);
+ private Color _baseNumColor = Color.darkGray;
+ private Color _baseNameColor = Color.black;
+ private Color _titleColor = Color.black;
+ private int _numOffset = 1;
-
- public void init()
- {
- retrieveParametersValues();
+ @Override
+ public void init() {
+// SecurityManager sm = System.getSecurityManager();
+ retrieveParametersValues();
+ }
+
+ private Color getSafeColor(String col, Color def) {
+ Color result;
+ try {
+ result = Color.decode(col);
+
+ } catch (Exception e) {
+ try {
+ result = Color.getColor(col, def);
+ } catch (Exception e2) {
+ System.err.println("'" + col + "' is not a valid color !");
+ return def;
+ }
}
-
- private Color getSafeColor(String col, Color def)
- {
- Color result;
- try
- {
- result = Color.decode(col);
-
- }
- catch(Exception e)
- {
- try
- {
- result = Color.getColor(col,def);
- }
- catch(Exception e2)
- {
- System.err.println("'"+col+"' is not a valid color !");
- return def;
- }
- }
- return result;
+ return result;
+ }
+
+ private String getParameterValue(String key, String def) {
+ String tmp;
+ tmp = getParameter(key);
+ if (tmp == null) {
+ return def;
+ } else {
+ return tmp;
}
-
-
- private String getParameterValue(String key, String def)
- {
- String tmp;
- tmp = getParameter(key);
- if (tmp==null)
- {
- return def;
- }
- else
- {
- return tmp;
- }
- }
- private String numColumnsOpt = "rows";
- private String numRowsOpt = "columns";
- private String algoOpt = "algorithm";
- private String backboneColorOpt = "backbone";
- private String backgroundColorOpt = "background";
- private String baseInnerColorOpt = "baseInner";
- private String baseNameColorOpt = "baseName";
- private String baseNumbersColorOpt = "baseNum";
- private String baseOutlineColorOpt = "baseOutline";
- private String bondColorOpt = "bp";
- private String periodNumOpt = "periodNum";
- private String sequenceOpt = "sequenceDBN";
- private String structureOpt = "structureDBN";
- private String titleOpt = "title";
- private String titleColorOpt = "titleColor";
- private String titleSizeOpt = "titleSize";
-
-
-
- public String[][] getParameterInfo() {
- String[][] info = {
- // Parameter Name Kind of Value Description
- {algoOpt, "String", "The drawing algorithm"},
- {backboneColorOpt, "Color", "A color for the backbone"},
- {backgroundColorOpt, "Color", "A color for the background"},
- {baseInnerColorOpt, "Color", "A color for the inner disc of a base drawing"},
- {baseNameColorOpt, "Color", "A color for the residue"},
- {baseNumbersColorOpt, "Color", "A color for the base numbers"},
- {baseOutlineColorOpt, "Color", "A color for the outer circle of a base drawing"},
- {bondColorOpt, "Color", "A color for the hydrogen bonds"},
- {sequenceOpt, "String", "A raw RNA sequence"},
- {structureOpt, "String", "An RNA structure in dot bracket notation (DBN)"},
- {periodNumOpt, "int", "Interval between two consecutive base numbers"},
- {titleOpt, "String", "A title for this RNA drawing"},
- {titleColorOpt, "Color", "A color for the title"},
- {titleSizeOpt, "int", "A font sized for the title"},
- };
- return info;
- }
+ }
+ private String numColumnsOpt = "rows";
+ private String numRowsOpt = "columns";
+ private String algoOpt = "algorithm";
+ private String backboneColorOpt = "backbone";
+ private String backgroundColorOpt = "background";
+ private String baseInnerColorOpt = "baseInner";
+ private String baseNameColorOpt = "baseName";
+ private String baseNumbersColorOpt = "baseNum";
+ private String baseOutlineColorOpt = "baseOutline";
+ private String bondColorOpt = "bp";
+ private String periodNumOpt = "periodNum";
+ private String sequenceOpt = "sequenceDBN";
+ private String structureOpt = "structureDBN";
+ private String titleOpt = "title";
+ private String titleColorOpt = "titleColor";
+ private String titleSizeOpt = "titleSize";
+ private String numOffsetOpt = "numOffset";
-
- private void retrieveParametersValues()
- {
- try
- {_numRows = Integer.parseInt(getParameterValue(numRowsOpt,""+_numRows));}
- catch(Exception e)
- { System.err.println("'"+getParameterValue(numRowsOpt,""+_numRows)+"' is not a integer value for the number of rows !");}
- try
- {_numColumns = Integer.parseInt(getParameterValue(numColumnsOpt,""+_numColumns));}
- catch(Exception e)
- { System.err.println("'"+getParameterValue(numColumnsOpt,""+_numColumns)+"' is not a integer value for the number of rows !");}
- getContentPane().removeAll();
- getContentPane().setLayout(new GridLayout(_numColumns,_numRows));
- for(int i=0;i<_numColumns;i++)
- {
- for(int j=0;j<_numRows;j++)
- {
- int x = 1+j+i*_numRows;
- String n=""+x;
- if((_numColumns==1)&&(_numRows==1))
- {
- n="";
- }
- _algo = getParameterValue(algoOpt+n,_algo);
- _backboneColor = getSafeColor(getParameterValue(backboneColorOpt+n,_backboneColor.toString()),_backboneColor);
- _backgroundColor = getSafeColor(getParameterValue(backgroundColorOpt+n,_backgroundColor.toString()),_backgroundColor);
- _bondColor = getSafeColor(getParameterValue(bondColorOpt+n,_bondColor.toString()),_bondColor);
- _baseInnerColor = getSafeColor(getParameterValue(baseInnerColorOpt+n,_baseInnerColor.toString()),_baseInnerColor);
- _baseNameColor = getSafeColor(getParameterValue(baseNameColorOpt+n,_baseNameColor.toString()),_baseNameColor);
- _baseNumColor = getSafeColor(getParameterValue(baseNumbersColorOpt+n,_baseNumColor.toString()),_baseNumColor);
- _baseOutlineColor = getSafeColor(getParameterValue(baseOutlineColorOpt+n,_baseOutlineColor.toString()),_baseOutlineColor);
- _sseq = getParameterValue(sequenceOpt+n,_sseq);
- _sstruct = getParameterValue(structureOpt+n,_sstruct);
- try
- {_periodResNum = Integer.parseInt(getParameterValue(periodNumOpt+n,""+_periodResNum));}
- catch(Exception e)
- { System.err.println("'"+getParameterValue(periodNumOpt+n,""+_periodResNum)+"' is not a integer value for the period of residue numbers !");}
- _title = getParameterValue(titleOpt+n,_title);
- _titleColor = getSafeColor(getParameterValue(titleColorOpt+n,_titleColor.toString()),_titleColor);
- try
- {_titleSize = Integer.parseInt(getParameterValue(titleSizeOpt+n,""+_titleSize));}
- catch(Exception e)
- { System.err.println("'"+getParameterValue(titleSizeOpt+n,""+_titleSize)+"' is not a integer value for the number of rows !");}
- //System.out.println(n+" "+_algo);
- VARNAPanel mainSurface = new VARNAPanel();
- int algoCode = (_algo.equals("circular")?VARNAPanel.DRAW_MODE_CIRCLE:VARNAPanel.DRAW_MODE_RADIATE);
- mainSurface.setRNA(_sseq, _sstruct, algoCode);
- mainSurface.setBackground(_backgroundColor);
- mainSurface.setNumPeriod(_periodResNum);
- mainSurface.setBackboneColor(_backboneColor);
- mainSurface.setBondColor(_bondColor);
- mainSurface.setBaseOutlineColor(_baseOutlineColor);
- mainSurface.setBaseInnerColor(_baseInnerColor);
- mainSurface.setBaseNumbersColor(_baseNumColor);
- mainSurface.setBaseNameColor(_baseNameColor);
- mainSurface.setTitleFontColor(_titleColor);
- mainSurface.setTitle(_title);
- mainSurface.setTitleFontSize(_titleSize);
- this.getContentPane().add(mainSurface);
- }
- }
- }
-
-
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- VARNAOfflineDemo mainFrame = new VARNAOfflineDemo();
-
- }
- private class ColorWrapper extends Color{
- String _name;
- public ColorWrapper(Color c,String name){
- super(c.getRGB());
- _name = name;
+ @Override
+ public String[][] getParameterInfo() {
+ String[][] info = {
+ // Parameter Name Kind of Value Description
+ {algoOpt, "String", "The drawing algorithm"},
+ {backboneColorOpt, "Color", "A color for the backbone"},
+ {backgroundColorOpt, "Color", "A color for the background"},
+ {baseInnerColorOpt, "Color", "A color for the inner disc of a base drawing"},
+ {baseNameColorOpt, "Color", "A color for the residue"},
+ {baseNumbersColorOpt, "Color", "A color for the base numbers"},
+ {baseOutlineColorOpt, "Color", "A color for the outer circle of a base drawing"},
+ {bondColorOpt, "Color", "A color for the hydrogen bonds"},
+ {sequenceOpt, "String", "A raw RNA sequence"},
+ {structureOpt, "String", "An RNA structure in dot bracket notation (DBN)"},
+ {periodNumOpt, "int", "Interval between two consecutive base numbers"},
+ {titleOpt, "String", "A title for this RNA drawing"},
+ {titleColorOpt, "Color", "A color for the title"},
+ {titleSizeOpt, "int", "A font sized for the title"},
+ {numOffsetOpt, "int", "An offset for bases numbering"},
+ };
+ return info;
}
-
- public String toString()
- {
- return _name;
+
+ private void retrieveParametersValues() {
+ try {
+ _numRows = Integer.parseInt(getParameterValue(numRowsOpt, "" + _numRows));
+ } catch (Exception e) {
+ System.err.println("'" + getParameterValue(numRowsOpt, "" + _numRows) + "' is not a integer value for the number of rows !");
+ }
+ try {
+ _numColumns = Integer.parseInt(getParameterValue(numColumnsOpt, "" + _numColumns));
+ } catch (Exception e) {
+ System.err.println("'" + getParameterValue(numColumnsOpt, "" + _numColumns) + "' is not a integer value for the number of rows !");
+ }
+ getContentPane().removeAll();
+ getContentPane().setLayout(new GridLayout(_numColumns, _numRows));
+ for (int i = 0; i < _numColumns; i++) {
+ for (int j = 0; j < _numRows; j++) {
+ int x = 1 + j + i * _numRows;
+ String n = "" + x;
+ if ((_numColumns == 1) && (_numRows == 1)) {
+ n = "";
+ }
+ _algo = getParameterValue(algoOpt + n, _algo);
+ _backboneColor = getSafeColor(getParameterValue(backboneColorOpt + n, _backboneColor.toString()), _backboneColor);
+ _backgroundColor = getSafeColor(getParameterValue(backgroundColorOpt + n, _backgroundColor.toString()), _backgroundColor);
+ _bondColor = getSafeColor(getParameterValue(bondColorOpt + n, _bondColor.toString()), _bondColor);
+ _baseInnerColor = getSafeColor(getParameterValue(baseInnerColorOpt + n, _baseInnerColor.toString()), _baseInnerColor);
+ _baseNameColor = getSafeColor(getParameterValue(baseNameColorOpt + n, _baseNameColor.toString()), _baseNameColor);
+ _baseNumColor = getSafeColor(getParameterValue(baseNumbersColorOpt + n, _baseNumColor.toString()), _baseNumColor);
+ _baseOutlineColor = getSafeColor(getParameterValue(baseOutlineColorOpt + n, _baseOutlineColor.toString()), _baseOutlineColor);
+ _sseq = getParameterValue(sequenceOpt + n, _sseq);
+ _sstruct = getParameterValue(structureOpt + n, _sstruct);
+ try {
+ _periodResNum = Integer.parseInt(getParameterValue(periodNumOpt + n, "" + _periodResNum));
+ } catch (Exception e) {
+ System.err.println("'" + getParameterValue(periodNumOpt + n, "" + _periodResNum) + "' is not a integer value for the period of residue numbers !");
+ }
+ try {
+ _numOffset = Integer.parseInt(getParameterValue(numOffsetOpt + n, "" + _numOffset));
+ } catch (Exception e) {
+ System.err.println("'" + getParameterValue(numOffsetOpt + n, "" + _numOffset) + "' is not a integer value for the offset of residue numbers !");
+ }
+ _title = getParameterValue(titleOpt + n, _title);
+// _title = getParameterValue(titleOpt + n, _title);
+ _titleColor = getSafeColor(getParameterValue(titleColorOpt + n, _titleColor.toString()), _titleColor);
+ try {
+ _titleSize = Integer.parseInt(getParameterValue(titleSizeOpt + n, "" + _titleSize));
+ } catch (Exception e) {
+ System.err.println("'" + getParameterValue(titleSizeOpt + n, "" + _titleSize) + "' is not a integer value for the number of rows !");
+ }
+ //System.out.println(n+" "+_algo);
+// VARNAPanel mainSurface = new VARNAPanel();
+ VARNAPanel mainSurface = _mainSurface;
+
+ int algoCode = (_algo.equals("circular") ? VARNAPanel.DRAW_MODE_CIRCLE : VARNAPanel.DRAW_MODE_RADIATE);
+ mainSurface.setRNA(_sseq, _sstruct, algoCode);
+ mainSurface.setBackground(_backgroundColor);
+ mainSurface.setNumPeriod(_periodResNum);
+ mainSurface.setNumOffset(_numOffset);
+ mainSurface.setBackboneColor(_backboneColor);
+ mainSurface.setBondColor(_bondColor);
+ mainSurface.setBaseOutlineColor(_baseOutlineColor);
+ mainSurface.setBaseInnerColor(_baseInnerColor);
+ mainSurface.setBaseNumbersColor(_baseNumColor);
+ mainSurface.setBaseNameColor(_baseNameColor);
+ mainSurface.setTitleFontColor(_titleColor);
+ mainSurface.setTitle(_title);
+ mainSurface.setTitleFontSize(_titleSize);
+ this.getContentPane().add(mainSurface);
+ mainSurface.setAutoFit(false);
+ }
+ }
+ }
+
+ /**
+ * @param args
+ */
+ public static void main(String[] args) {
+ // TODO Auto-generated method stub
+ VARNAOfflineDemo mainFrame = new VARNAOfflineDemo();
+
}
- }
+ private class ColorWrapper extends Color {
+
+ String _name;
+
+ public ColorWrapper(Color c, String name) {
+ super(c.getRGB());
+ _name = name;
+ }
+
+ public String toString() {
+ return _name;
+ }
+ }
}
diff -U 3 -H -d -r -N -- original_varna_2.0/VARNADemo.java src/VARNADemo.java
--- original_varna_2.0/VARNADemo.java 2007-10-11 14:48:00.000000000 +0200
+++ src/VARNADemo.java 2008-03-24 12:24:25.000000000 +0100
@@ -16,7 +16,6 @@
along with this program. If not, see .
*/
-import java.applet.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
@@ -29,12 +28,6 @@
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
-import java.awt.event.InputMethodEvent;
-import java.awt.event.InputMethodListener;
-import java.awt.event.KeyEvent;
-import java.awt.event.KeyListener;
-import java.awt.event.WindowEvent;
-import java.awt.event.WindowListener;
/**
* An RNA 2d Panel demo applet
* @author Yann Ponty
diff -U 3 -H -d -r -N -- original_varna_2.0/VARNAmulti.form src/VARNAmulti.form
--- original_varna_2.0/VARNAmulti.form 1970-01-01 01:00:00.000000000 +0100
+++ src/VARNAmulti.form 2008-07-16 10:59:05.000000000 +0200
@@ -0,0 +1,60 @@
+
+
+
diff -U 3 -H -d -r -N -- original_varna_2.0/VARNAmulti.java src/VARNAmulti.java
--- original_varna_2.0/VARNAmulti.java 1970-01-01 01:00:00.000000000 +0100
+++ src/VARNAmulti.java 2008-07-16 10:59:05.000000000 +0200
@@ -0,0 +1,207 @@
+
+import java.awt.KeyEventDispatcher;
+import java.awt.KeyboardFocusManager;
+import java.awt.event.KeyEvent;
+import java.io.File;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import multi.RNASecStrSel;
+
+/*
+ * VARNAmulti.java
+ *
+ * Created on 24. březen 2008, 11:07
+ */
+import org.apache.commons.cli.BasicParser;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import varna.VARNAPanel;
+
+/**
+ *
+ * @author lopik
+ */
+public class VARNAmulti extends javax.swing.JFrame {
+
+ /** Creates new form VARNAmulti */
+ public VARNAmulti() {
+ initComponents();
+ /*
+ varnaPanel.setAutoCenter(true);
+ varnaPanel.setRNA(
+ "CAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIA",
+ "..(((((...(((((...(((((...(((((.....)))))...))))).....(((((...(((((.....)))))...))))).....)))))...)))))..");
+ varnaPanel.setAutoFit(true);
+ */
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // //GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jSplitPane1 = new javax.swing.JSplitPane();
+ fastaViewPanel2 = new multi.FastaViewPanel();
+ fastaViewPanel1 = new multi.FastaViewPanel();
+
+ jSplitPane1.setDividerLocation(400);
+ jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
+ jSplitPane1.setRightComponent(fastaViewPanel2);
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
+ setTitle("VARNA multi view");
+ addKeyListener(new java.awt.event.KeyAdapter() {
+ public void keyPressed(java.awt.event.KeyEvent evt) {
+ formKeyPressed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(fastaViewPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 939, Short.MAX_VALUE)
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(fastaViewPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 673, Short.MAX_VALUE)
+ );
+
+ pack();
+ }// //GEN-END:initComponents
+
+private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
+ System.out.println("KEY:" + evt);
+}//GEN-LAST:event_formKeyPressed
+
+ /**
+ * @param args the command line arguments
+ */
+ public static void main(String args[]) {
+ KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
+
+ public boolean dispatchKeyEvent(KeyEvent e) {
+ if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_Q) {
+ System.exit(0);
+ }
+ System.out.println(e.getKeyCode() + " : " + e.getKeyChar());
+ return false;
+ }
+ });
+
+ final VARNAmulti varna = new VARNAmulti();
+ if( varna.proceedParams(args) ) {
+ java.awt.EventQueue.invokeLater(new Runnable() {
+ public void run() {
+ varna.setVisible(true);
+ }
+ });
+ } else {
+ System.exit(1);
+ }
+ }
+
+ @SuppressWarnings("static-access")
+ private boolean proceedParams(String[] paramList) {
+ Options opt = new Options();
+ opt.addOption("h", "help", false, "print this page");
+ opt.addOption( OptionBuilder.withArgName("file").hasArg().withDescription("load fasta-align file").withLongOpt("input-align").create());
+ opt.addOption( OptionBuilder.withArgName("file").hasArg().withDescription("load fasta file").create("i"));
+ opt.addOption( OptionBuilder.withArgName("file").hasArg().withDescription("write JPEG").create("sJPEG"));
+ opt.addOption( OptionBuilder.withArgName("file").hasArg().withDescription("write SVG").create("sSVG"));
+ opt.addOption( OptionBuilder.withArgName("scale").hasArg().withDescription("scale SVG image").withLongOpt("svg-scale").create());
+ opt.addOption( OptionBuilder.withArgName("width").hasArg().withDescription("output image width").withLongOpt("width").create());
+ opt.addOption( OptionBuilder.withArgName("height").hasArg().withDescription("output image height").withLongOpt("height").create());
+ opt.addOption( OptionBuilder.withArgName("num-period").hasArg().withDescription("base numbering period").withLongOpt("num-period").create());
+ opt.addOption( OptionBuilder.withArgName("num-offset").hasArg().withDescription("base numbering offset").withLongOpt("num-offset").create());
+
+ BasicParser parser = new BasicParser();
+ try {
+ CommandLine cl = parser.parse(opt, paramList);
+ int width = Integer.parseInt( cl.getOptionValue("width", "400") );
+ int height = Integer.parseInt( cl.getOptionValue("height", "400") );
+ VARNAPanel varnaPanel = fastaViewPanel1.getVarnaPanel();
+
+ varnaPanel.setNumPeriod( Integer.parseInt( cl.getOptionValue("num-period", "5") ) );
+ varnaPanel.setNumOffset( Integer.parseInt( cl.getOptionValue("num-offset", "1") ) );
+ if( cl.hasOption("h") ) {
+ HelpFormatter f = new HelpFormatter();
+ f.printHelp("varna", opt);
+ return false;
+ }
+ if( cl.hasOption("input-align") ) {
+ String fname = cl.getOptionValue("input-align");
+ fastaViewPanel1.loadFile(new File(fname));
+// varnaPanel.setRNA(RNASecStrSel.loadSecStr(fname));
+ }
+ if( cl.hasOption("i") ) {
+ String fname = cl.getOptionValue("i");
+ varnaPanel.setRNA(RNASecStrSel.loadSecStr(fname));
+ }
+ if( cl.hasOption("sJPEG") ) {
+ String fname = cl.getOptionValue("sJPEG");
+ varnaPanel.setSize(width, height);
+ varnaPanel.saveToJPEG(cl.getOptionValue("sJPEG"));
+ System.exit(0);
+ }
+ if( cl.hasOption("sSVG") ) {
+ String fname = cl.getOptionValue("sSVG");
+ if( cl.hasOption("width") || cl.hasOption("height") ) {
+ double scale = Double.parseDouble(cl.getOptionValue("svg-scale", "1.0"));
+ varnaPanel.setSize(width, height);
+ varnaPanel.saveToSVG(cl.getOptionValue("sSVG"), scale);
+ } else {
+ varnaPanel.setSize(width, height);
+ varnaPanel.saveToSVG(cl.getOptionValue("sSVG"));
+ }
+ System.exit(0);
+ }
+
+
+ } catch (ParseException ex) {
+ Logger.getLogger(VARNAmulti.class.getName()).log(Level.SEVERE, null, ex);
+ }
+ return true;
+//
+// for( int param = 0; param < paramList.length; param++ ) {
+// if( "-h".equals(paramList[param]) ) {
+// printCommandLineParams();
+// return false;
+// }
+// if( "-i".equals(paramList[param]) ) {
+// if( param < paramList.length - 1 ) param++;
+// fastaViewPanel1.getVarnaPanel().setRNA(RNASecStrSel.loadSecStr(paramList[param]));
+// continue;
+// }
+// if( "-sJPEG".equals(paramList[param]) ) {
+// if( param < paramList.length - 1 ) param++;
+// fastaViewPanel1.getVarnaPanel().saveToJPEG(paramList[param]);
+// System.exit(0);
+// continue;
+// }
+// if( "-sSVG".equals(paramList[param]) ) {
+// if( param < paramList.length - 1 ) param++;
+// fastaViewPanel1.getVarnaPanel().saveToSVG(paramList[param]);
+// System.exit(0);
+// continue;
+// }
+// printCommandLineParams();
+// return false;
+// }
+// return true;
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private multi.FastaViewPanel fastaViewPanel1;
+ private multi.FastaViewPanel fastaViewPanel2;
+ private javax.swing.JSplitPane jSplitPane1;
+ // End of variables declaration//GEN-END:variables
+
+}
diff -U 3 -H -d -r -N -- original_varna_2.0/applet/AlignApplet.form src/applet/AlignApplet.form
--- original_varna_2.0/applet/AlignApplet.form 1970-01-01 01:00:00.000000000 +0100
+++ src/applet/AlignApplet.form 2008-07-16 11:57:33.000000000 +0200
@@ -0,0 +1,31 @@
+
+
+
diff -U 3 -H -d -r -N -- original_varna_2.0/applet/AlignApplet.java src/applet/AlignApplet.java
--- original_varna_2.0/applet/AlignApplet.java 1970-01-01 01:00:00.000000000 +0100
+++ src/applet/AlignApplet.java 2008-07-16 11:57:33.000000000 +0200
@@ -0,0 +1,246 @@
+/*
+ * AlignApplet.java
+ *
+ * Created on 16. červenec 2008, 9:10
+ */
+
+package applet;
+
+import java.awt.Color;
+import java.awt.GridLayout;
+import java.io.StringReader;
+import varna.VARNAPanel;
+
+/**
+ *
+ * @author lopik
+ */
+public class AlignApplet extends javax.swing.JApplet {
+
+ /** Initializes the applet AlignApplet */
+ public void init() {
+ try {
+ java.awt.EventQueue.invokeAndWait(new Runnable() {
+ public void run() {
+ initComponents();
+ fastaViewPanel.setAppletView(true);
+ retrieveParametersValues();
+ }
+ });
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+// SecurityManager sm = System.getSecurityManager();
+ }
+
+
+ // Applet assignable parameters
+ private String _algo = "radiate";
+ private Color _backgroundColor = Color.white;
+ private String _sseq = "CAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIA";
+ private String _sstruct = "..(((((...(((((...(((((...(((((.....)))))...))))).....(((((...(((((.....)))))...))))).....)))))...)))))..";
+ private int _periodResNum = 5;
+ private int _numRows = 1;
+ private int _numColumns = 1;
+ private String _title = "";
+ private int _titleSize = 18;
+ private Color _backboneColor = Color.black;
+ private Color _bondColor = Color.blue;
+ private Color _baseOutlineColor = Color.darkGray;
+ private Color _baseInnerColor = new Color(230, 230, 230);
+ private Color _baseNumColor = Color.darkGray;
+ private Color _baseNameColor = Color.black;
+ private Color _titleColor = Color.black;
+ private int _numOffset = 1;
+
+ private Color getSafeColor(String col, Color def) {
+ Color result;
+ try {
+ result = Color.decode(col);
+
+ } catch (Exception e) {
+ try {
+ result = Color.getColor(col, def);
+ } catch (Exception e2) {
+ System.err.println("'" + col + "' is not a valid color !");
+ return def;
+ }
+ }
+ return result;
+ }
+
+ private String getParameterValue(String key, String def) {
+ String tmp;
+ tmp = getParameter(key);
+ if (tmp == null) {
+ return def;
+ } else {
+ return tmp;
+ }
+ }
+ private String numColumnsOpt = "rows";
+ private String numRowsOpt = "columns";
+ private String algoOpt = "algorithm";
+ private String backboneColorOpt = "backbone";
+ private String backgroundColorOpt = "background";
+ private String baseInnerColorOpt = "baseInner";
+ private String baseNameColorOpt = "baseName";
+ private String baseNumbersColorOpt = "baseNum";
+ private String baseOutlineColorOpt = "baseOutline";
+ private String bondColorOpt = "bp";
+ private String periodNumOpt = "periodNum";
+ private String sequenceOpt = "sequenceDBN";
+ private String structureOpt = "structureDBN";
+ private String titleOpt = "title";
+ private String titleColorOpt = "titleColor";
+ private String titleSizeOpt = "titleSize";
+ private String numOffsetOpt = "numOffset";
+ private String alignStructureOpt = "alignStructure";
+
+ @Override
+ public String[][] getParameterInfo() {
+ String[][] info = {
+ // Parameter Name Kind of Value Description
+ {algoOpt, "String", "The drawing algorithm"},
+ {backboneColorOpt, "Color", "A color for the backbone"},
+ {backgroundColorOpt, "Color", "A color for the background"},
+ {baseInnerColorOpt, "Color", "A color for the inner disc of a base drawing"},
+ {baseNameColorOpt, "Color", "A color for the residue"},
+ {baseNumbersColorOpt, "Color", "A color for the base numbers"},
+ {baseOutlineColorOpt, "Color", "A color for the outer circle of a base drawing"},
+ {bondColorOpt, "Color", "A color for the hydrogen bonds"},
+ {sequenceOpt, "String", "A raw RNA sequence"},
+ {structureOpt, "String", "An RNA structure in dot bracket notation (DBN)"},
+ {periodNumOpt, "int", "Interval between two consecutive base numbers"},
+ {titleOpt, "String", "A title for this RNA drawing"},
+ {titleColorOpt, "Color", "A color for the title"},
+ {titleSizeOpt, "int", "A font sized for the title"},
+ {numOffsetOpt, "int", "An offset for bases numbering"},
+ {alignStructureOpt, "String", "Fasta align structures"},
+ };
+ return info;
+ }
+
+ private void retrieveParametersValues() {
+ try {
+ _numRows = Integer.parseInt(getParameterValue(numRowsOpt, "" + _numRows));
+ } catch (Exception e) {
+ System.err.println("'" + getParameterValue(numRowsOpt, "" + _numRows) + "' is not a integer value for the number of rows !");
+ }
+ try {
+ _numColumns = Integer.parseInt(getParameterValue(numColumnsOpt, "" + _numColumns));
+ } catch (Exception e) {
+ System.err.println("'" + getParameterValue(numColumnsOpt, "" + _numColumns) + "' is not a integer value for the number of rows !");
+ }
+// getContentPane().removeAll();
+// getContentPane().setLayout(new GridLayout(_numColumns, _numRows));
+// for (int i = 0; i < _numColumns; i++) {
+// for (int j = 0; j < _numRows; j++) {
+// int x = 1 + j + i * _numRows;
+ String n = "";// + x;
+// if ((_numColumns == 1) && (_numRows == 1)) {
+// n = "";
+// }
+ _algo = getParameterValue(algoOpt + n, _algo);
+ _backboneColor = getSafeColor(getParameterValue(backboneColorOpt + n, _backboneColor.toString()), _backboneColor);
+ _backgroundColor = getSafeColor(getParameterValue(backgroundColorOpt + n, _backgroundColor.toString()), _backgroundColor);
+ _bondColor = getSafeColor(getParameterValue(bondColorOpt + n, _bondColor.toString()), _bondColor);
+ _baseInnerColor = getSafeColor(getParameterValue(baseInnerColorOpt + n, _baseInnerColor.toString()), _baseInnerColor);
+ _baseNameColor = getSafeColor(getParameterValue(baseNameColorOpt + n, _baseNameColor.toString()), _baseNameColor);
+ _baseNumColor = getSafeColor(getParameterValue(baseNumbersColorOpt + n, _baseNumColor.toString()), _baseNumColor);
+ _baseOutlineColor = getSafeColor(getParameterValue(baseOutlineColorOpt + n, _baseOutlineColor.toString()), _baseOutlineColor);
+ _sseq = getParameterValue(sequenceOpt + n, _sseq);
+ _sstruct = getParameterValue(structureOpt + n, _sstruct);
+ try {
+ _periodResNum = Integer.parseInt(getParameterValue(periodNumOpt + n, "" + _periodResNum));
+ } catch (Exception e) {
+ System.err.println("'" + getParameterValue(periodNumOpt + n, "" + _periodResNum) + "' is not a integer value for the period of residue numbers !");
+ }
+ try {
+ _numOffset = Integer.parseInt(getParameterValue(numOffsetOpt + n, "" + _numOffset));
+ } catch (Exception e) {
+ System.err.println("'" + getParameterValue(numOffsetOpt + n, "" + _numOffset) + "' is not a integer value for the offset of residue numbers !");
+ }
+ _title = getParameterValue(titleOpt + n, _title);
+// _title = getParameterValue(titleOpt + n, _title);
+ _titleColor = getSafeColor(getParameterValue(titleColorOpt + n, _titleColor.toString()), _titleColor);
+ try {
+ _titleSize = Integer.parseInt(getParameterValue(titleSizeOpt + n, "" + _titleSize));
+ } catch (Exception e) {
+ System.err.println("'" + getParameterValue(titleSizeOpt + n, "" + _titleSize) + "' is not a integer value for the number of rows !");
+ }
+ //System.out.println(n+" "+_algo);
+// VARNAPanel mainSurface = new VARNAPanel();
+ VARNAPanel mainSurface = fastaViewPanel.getVarnaPanel();
+
+
+ int algoCode = (_algo.equals("circular") ? VARNAPanel.DRAW_MODE_CIRCLE : VARNAPanel.DRAW_MODE_RADIATE);
+ mainSurface.setRNA(_sseq, _sstruct, algoCode);
+ mainSurface.setBackground(_backgroundColor);
+ mainSurface.setNumPeriod(_periodResNum);
+ mainSurface.setNumOffset(_numOffset);
+ mainSurface.setBackboneColor(_backboneColor);
+ mainSurface.setBondColor(_bondColor);
+ mainSurface.setBaseOutlineColor(_baseOutlineColor);
+ mainSurface.setBaseInnerColor(_baseInnerColor);
+ mainSurface.setBaseNumbersColor(_baseNumColor);
+ mainSurface.setBaseNameColor(_baseNameColor);
+ mainSurface.setTitleFontColor(_titleColor);
+ mainSurface.setTitle(_title);
+ mainSurface.setTitleFontSize(_titleSize);
+
+
+ String alignStructure = getParameter(alignStructureOpt);
+ alignStructure = alignStructure.replaceAll(";", "\n");
+ System.out.println("ALIGN_STRUCTURE:" + alignStructure);
+ fastaViewPanel.load( new StringReader(alignStructure));
+// this.getContentPane().add(mainSurface);
+// mainSurface.setAutoFit(false);
+// }
+// }
+ }
+
+ private class ColorWrapper extends Color {
+
+ String _name;
+
+ public ColorWrapper(Color c, String name) {
+ super(c.getRGB());
+ _name = name;
+ }
+
+ public String toString() {
+ return _name;
+ }
+ }
+
+
+ /** This method is called from within the init() method to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // //GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ fastaViewPanel = new multi.FastaViewPanel();
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(fastaViewPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 735, Short.MAX_VALUE)
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(fastaViewPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE)
+ );
+ }// //GEN-END:initComponents
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private multi.FastaViewPanel fastaViewPanel;
+ // End of variables declaration//GEN-END:variables
+
+}
diff -U 3 -H -d -r -N -- original_varna_2.0/multi/FastaViewPanel.form src/multi/FastaViewPanel.form
--- original_varna_2.0/multi/FastaViewPanel.form 1970-01-01 01:00:00.000000000 +0100
+++ src/multi/FastaViewPanel.form 2008-09-15 15:32:52.000000000 +0200
@@ -0,0 +1,189 @@
+
+
+
diff -U 3 -H -d -r -N -- original_varna_2.0/multi/FastaViewPanel.java src/multi/FastaViewPanel.java
--- original_varna_2.0/multi/FastaViewPanel.java 1970-01-01 01:00:00.000000000 +0100
+++ src/multi/FastaViewPanel.java 2008-09-15 15:32:52.000000000 +0200
@@ -0,0 +1,375 @@
+/*
+ * FastaViewPanel.java
+ *
+ * Created on 24. březen 2008, 18:37
+ */
+package multi;
+
+import java.awt.Color;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.Reader;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.swing.DefaultListModel;
+import javax.swing.JFileChooser;
+import javax.swing.JOptionPane;
+import varna.RNASecStr;
+import varna.VARNAPanel;
+
+/**
+ *
+ * @author lopik
+ */
+public class FastaViewPanel extends javax.swing.JPanel {
+
+ class SecStrListItem {
+ RNASecStr secStr;
+ String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public RNASecStr getSecStr() {
+ return secStr;
+ }
+
+ public SecStrListItem(RNASecStr secStr, String name) {
+ this.secStr = secStr;
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+
+ }
+ List rnaStructureList = new ArrayList();
+ Map rnaAlignmentMap = new HashMap();
+
+ /** Creates new form FastaViewPanel */
+ public FastaViewPanel() {
+ initComponents();
+ varnaPanel.setAutoFit(jToggleButtonAutoFit.isSelected());
+ varnaPanel.setTitleFontSize(12);
+ varnaPanel.setTitleFontStyle("BOLD");
+// varnaPanel.setTitleFontColor(new Color( 0, 60, 110 ) );
+ varnaPanel2.setAutoFit(false);
+ varnaPanel2.setTitleFontSize(12);
+ varnaPanel2.setTitleFontStyle("BOLD");
+// varnaPanel2.setTitleFontColor(new Color( 0, 60, 110 ) );
+ }
+
+ public void setAppletView( boolean applet ) {
+ jTextFieldFileName.setVisible(!applet);
+ jButtonOpenFile.setVisible(!applet);
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // //GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jButtonLoadSelection = new javax.swing.JButton();
+ jSplitPane2 = new javax.swing.JSplitPane();
+ jPanel1 = new javax.swing.JPanel();
+ jTextFieldFileName = new javax.swing.JTextField();
+ jButtonOpenFile = new javax.swing.JButton();
+ jScrollPane1 = new javax.swing.JScrollPane();
+ jListStructureList = new javax.swing.JList();
+ jToggleButtonAutoFit = new javax.swing.JToggleButton();
+ jSplitPane1 = new javax.swing.JSplitPane();
+ varnaPanel = new varna.VARNAPanel();
+ varnaPanel2 = new varna.VARNAPanel();
+
+ jButtonLoadSelection.setText("Load selection");
+ jButtonLoadSelection.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jButtonLoadSelectionActionPerformed(evt);
+ }
+ });
+
+ setBorder(javax.swing.BorderFactory.createEtchedBorder());
+
+ jTextFieldFileName.setEditable(false);
+
+ jButtonOpenFile.setText("open");
+ jButtonOpenFile.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jButtonOpenFileActionPerformed(evt);
+ }
+ });
+
+ jListStructureList.setModel(new DefaultListModel());
+ jListStructureList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
+ public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
+ jListStructureListValueChanged(evt);
+ }
+ });
+ jScrollPane1.setViewportView(jListStructureList);
+
+ jToggleButtonAutoFit.setText("autoFit");
+ jToggleButtonAutoFit.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jToggleButtonAutoFitActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
+ jPanel1.setLayout(jPanel1Layout);
+ jPanel1Layout.setHorizontalGroup(
+ jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGap(0, 232, Short.MAX_VALUE)
+ .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanel1Layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
+ .addComponent(jTextFieldFileName, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jButtonOpenFile))
+ .addComponent(jToggleButtonAutoFit)
+ .addComponent(jScrollPane1, 0, 0, Short.MAX_VALUE))
+ .addContainerGap()))
+ );
+ jPanel1Layout.setVerticalGroup(
+ jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGap(0, 393, Short.MAX_VALUE)
+ .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanel1Layout.createSequentialGroup()
+ .addGap(5, 5, 5)
+ .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(jButtonOpenFile)
+ .addComponent(jTextFieldFileName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jToggleButtonAutoFit)
+ .addGap(5, 5, 5)))
+ );
+
+ jSplitPane2.setLeftComponent(jPanel1);
+
+ jSplitPane1.setDividerLocation(700);
+ jSplitPane1.setDividerSize(8);
+
+ varnaPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
+ varnaPanel.setRNA(null);
+ varnaPanel.setAutoFit(false);
+ jSplitPane1.setLeftComponent(varnaPanel);
+
+ varnaPanel2.setAutoFit(true);
+ varnaPanel2.setBaseInnerColor(new java.awt.Color(255, 0, 51));
+ jSplitPane1.setRightComponent(varnaPanel2);
+
+ jSplitPane2.setRightComponent(jSplitPane1);
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(jSplitPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 1030, Short.MAX_VALUE)
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(jSplitPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE)
+ );
+ }// //GEN-END:initComponents
+
+private void jButtonOpenFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOpenFileActionPerformed
+ JFileChooser jFileChooser = new JFileChooser( "/home/lopik/prog/python" );
+ if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
+ File file = jFileChooser.getSelectedFile();
+ loadFile(file);
+ jTextFieldFileName.setText(file.getName());
+ }
+
+}//GEN-LAST:event_jButtonOpenFileActionPerformed
+
+private void jListStructureListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListStructureListValueChanged
+ RNASecStrSel item = (RNASecStrSel) ((SecStrListItem) jListStructureList.getSelectedValue()).getSecStr();
+ if (item == null) {
+ return;
+ }
+ varnaPanel.setRNA(item);
+ varnaPanel.fitStructure();
+ varnaPanel.setTitle( this.trimStructureName( item.getName() ) );
+ varnaPanel.setTitleFontSize(12);
+ varnaPanel.setTitleFontStyle("BOLD");
+// varnaPanel.setTitleFontColor(new Color( 0, 60, 110 ) );
+
+// System.out.println(item.getName());
+ Matcher m = Pattern.compile("IDL:([0-9]+) .*").matcher(item.getName());
+ m.find();
+ if (m.matches()) {
+// System.out.println("pair: " + rnaAlignmentMap.get(m.group(1)).getName() );
+ RNASecStrSel itemPair = rnaAlignmentMap.get(m.group(1));
+ varnaPanel2.setRNA(itemPair);
+ varnaPanel2.fitStructure();
+ varnaPanel2.setTitle( this.trimStructureName( itemPair.getName() ) );
+ if (itemPair.getSelection() != null) {
+ varnaPanel2.setStructureSelection(itemPair.getSelection());
+ }
+ }
+
+ if (item.getSelection() != null) {
+ varnaPanel.setStructureSelection(item.getSelection());
+ }
+}//GEN-LAST:event_jListStructureListValueChanged
+
+private void jToggleButtonAutoFitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButtonAutoFitActionPerformed
+ varnaPanel.setAutoFit(jToggleButtonAutoFit.isSelected());
+}//GEN-LAST:event_jToggleButtonAutoFitActionPerformed
+
+private void jButtonLoadSelectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLoadSelectionActionPerformed
+ String str = JOptionPane.showInputDialog(this, "Enter selection map ('-' is non-selected base)");
+ varnaPanel.setStructureSelection(str);
+}//GEN-LAST:event_jButtonLoadSelectionActionPerformed
+ public void loadFile(File file) {
+ try {
+ load(new FileReader(file));
+ } catch (FileNotFoundException ex) {
+ Logger.getLogger(FastaViewPanel.class.getName()).log(Level.SEVERE, null, ex);
+ }
+ }
+ public void load( Reader reader ) {
+ List loadList = new ArrayList();
+ loadList.clear();
+ BufferedReader bis = null;
+ try {
+ bis = new BufferedReader( reader );
+ String line;
+ boolean structStarted = false;
+ String name = "";
+ String[] lines = new String[3];
+ int lineCount = 0;
+ while (null != (line = bis.readLine())) {
+ if (line.startsWith(">")) {
+ if (lineCount == 1) {
+ String seq = "";
+ for (int i = 0; i < lines[0].length(); i++) {
+ seq += "n";
+ }
+ loadList.add(new RNASecStrSel(seq, lines[0], name));
+ } else if (lineCount == 2) {
+ loadList.add(new RNASecStrSel(lines[0], lines[1], name));
+ } else if (lineCount == 3) {
+ loadList.add(new RNASecStrSel(lines[0], lines[1], name, lines[2]));
+ }
+
+ name = line.substring(1);
+ structStarted = true;
+ lineCount = 0;
+ } else if (lineCount < 3) {
+ lines[lineCount] = line;
+ lineCount++;
+ }
+ }
+ if (lineCount == 1) {
+ String seq = "";
+ for (int i = 0; i < lines[0].length(); i++) {
+ seq += "n";
+ }
+ loadList.add(new RNASecStrSel(seq, lines[0], name));
+ } else if (lineCount == 2) {
+ loadList.add(new RNASecStrSel(lines[0], lines[1], name));
+ } else if (lineCount == 3) {
+ loadList.add(new RNASecStrSel(lines[0], lines[1], name, lines[2]));
+ }
+ parseStructureList(loadList);
+ updateStructureList();
+
+ } catch (ParseException ex) {
+ Logger.getLogger(FastaViewPanel.class.getName()).log(Level.SEVERE, null, ex);
+ } catch (FileNotFoundException ex) {
+ Logger.getLogger(FastaViewPanel.class.getName()).log(Level.SEVERE, null, ex);
+ } catch (IOException ex) {
+ Logger.getLogger(FastaViewPanel.class.getName()).log(Level.SEVERE, null, ex);
+ } finally {
+ try {
+ bis.close();
+ } catch (IOException ex) {
+ Logger.getLogger(FastaViewPanel.class.getName()).log(Level.SEVERE, null, ex);
+ }
+ }
+ }
+
+ void parseStructureList(List list) {
+ rnaStructureList.clear();
+ for (RNASecStrSel str : list) {
+ Matcher m = Pattern.compile("IDS:([0-9]+) .*").matcher(str.getName());
+ m.find();
+ if (m.matches()) {
+ String key = m.group(1);
+ rnaAlignmentMap.put(key, str);
+ } else {
+ rnaStructureList.add(str);
+ }
+ }
+ }
+
+ protected String trimStructureName( String str ) {
+// Matcher m = Pattern.compile("ID[SL]:[0-9]+ +(.*)$").matcher(str);
+ Matcher m = Pattern.compile("[^\\|]*\\|(.*)").matcher(str);
+ m.find();
+ if( m.matches() ) {
+ return m.group(1);
+ } else {
+ return str;
+ }
+ }
+
+ protected String trimStructureNameList( String str ) {
+ Matcher m = Pattern.compile("IDL:[0-9]+.*score: (.*)$").matcher(str);
+ m.find();
+ if( m.matches() ) {
+ return "s: " + m.group(1);
+ } else {
+ return str;
+ }
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JButton jButtonLoadSelection;
+ private javax.swing.JButton jButtonOpenFile;
+ private javax.swing.JList jListStructureList;
+ private javax.swing.JPanel jPanel1;
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JSplitPane jSplitPane1;
+ private javax.swing.JSplitPane jSplitPane2;
+ private javax.swing.JTextField jTextFieldFileName;
+ private javax.swing.JToggleButton jToggleButtonAutoFit;
+ private varna.VARNAPanel varnaPanel;
+ private varna.VARNAPanel varnaPanel2;
+ // End of variables declaration//GEN-END:variables
+
+ private void updateStructureList() {
+ DefaultListModel model = (DefaultListModel) jListStructureList.getModel();
+ model.clear();
+ for( RNASecStr structure : rnaStructureList ) {
+ model.addElement(new SecStrListItem( structure, this.trimStructureNameList( structure.getName() ) ) );
+ }
+ jListStructureList.setSelectedIndex(0);
+ }
+
+ public VARNAPanel getVarnaPanel() {
+ return varnaPanel;
+ }
+
+}
diff -U 3 -H -d -r -N -- original_varna_2.0/multi/RNASecStrSel.java src/multi/RNASecStrSel.java
--- original_varna_2.0/multi/RNASecStrSel.java 1970-01-01 01:00:00.000000000 +0100
+++ src/multi/RNASecStrSel.java 2008-04-30 11:42:04.000000000 +0200
@@ -0,0 +1,117 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package multi;
+
+import java.io.BufferedReader;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.Reader;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import varna.RNASecStr;
+
+/**
+ *
+ * @author lopik
+ */
+public class RNASecStrSel extends RNASecStr {
+
+ protected String selection;
+
+ /**
+ * Get the value of selection
+ *
+ * @return the value of selection
+ */
+ public String getSelection() {
+ return this.selection;
+ }
+
+ /**
+ * Set the value of selection
+ *
+ * @param newselection new value of selection
+ */
+ public void setSelection(String newselection) {
+ this.selection = newselection;
+ }
+
+ public RNASecStrSel(String seq, String str, String name) throws ParseException {
+ super(seq, str, name);
+ }
+
+ public RNASecStrSel(String seq, String str, String name, String selection) throws ParseException {
+ super(seq, str, name);
+ this.selection = selection;
+ }
+
+ static List loadFile(Reader reader) {
+ List loadList = new ArrayList();
+ loadList.clear();
+ BufferedReader bis = null;
+ try {
+ bis = new BufferedReader(reader);
+ String line;
+ boolean structStarted = false;
+ String name = "";
+ String[] lines = new String[3];
+ int lineCount = 0;
+ while (null != (line = bis.readLine())) {
+ if (line.startsWith(">")) {
+ if( lineCount == 1 ) {
+ String seq = "";
+ for( int i=0;i
+
+
diff -U 3 -H -d -r -N -- original_varna_2.0/varna/AboutDialog.java src/varna/AboutDialog.java
--- original_varna_2.0/varna/AboutDialog.java 1970-01-01 01:00:00.000000000 +0100
+++ src/varna/AboutDialog.java 2008-09-15 23:51:29.000000000 +0200
@@ -0,0 +1,117 @@
+/*
+ * AboutDialog.java
+ *
+ * Created on 11. září 2008, 12:16
+ */
+
+package varna;
+
+/**
+ *
+ * @author lopik
+ */
+public class AboutDialog extends javax.swing.JDialog {
+
+ /** Creates new form AboutDialog */
+ public AboutDialog(java.awt.Frame parent, boolean modal) {
+ super(parent, modal);
+ initComponents();
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // //GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jLabel1 = new javax.swing.JLabel();
+ jScrollPane1 = new javax.swing.JScrollPane();
+ jTextPane1 = new javax.swing.JTextPane();
+ jButtonClose = new javax.swing.JButton();
+ jLabel2 = new javax.swing.JLabel();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ jLabel1.setFont(new java.awt.Font("Dialog", 1, 18));
+ jLabel1.setText("VARNA align");
+
+ jTextPane1.setBackground(javax.swing.UIManager.getDefaults().getColor("Panel.background"));
+ jTextPane1.setContentType("text/html");
+ jTextPane1.setEditable(false);
+ jTextPane1.setText("\n \n\n \n \n \n VARNA align is based on VARNA created by Yann Ponty (http://www.lri.fr/~ponty/VARNA)
\n Author of modifications is Petr Hlubuček (hlopo@atlas.cz).
\n Source code can be downloaded from http://iresite.org/VARNA. \n
\n \n\n");
+ jScrollPane1.setViewportView(jTextPane1);
+
+ jButtonClose.setText("Close");
+ jButtonClose.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jButtonCloseActionPerformed(evt);
+ }
+ });
+
+ jLabel2.setText("Version: 1.0.1");
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 552, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(jLabel1)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addComponent(jLabel2)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 414, Short.MAX_VALUE)
+ .addComponent(jButtonClose)))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jLabel1)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(jButtonClose)
+ .addComponent(jLabel2))
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ pack();
+ }// //GEN-END:initComponents
+
+private void jButtonCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCloseActionPerformed
+ this.setVisible(false);
+}//GEN-LAST:event_jButtonCloseActionPerformed
+
+ /**
+ * @param args the command line arguments
+ */
+ public static void main(String args[]) {
+ java.awt.EventQueue.invokeLater(new Runnable() {
+ public void run() {
+ AboutDialog dialog = new AboutDialog(new javax.swing.JFrame(), true);
+ dialog.addWindowListener(new java.awt.event.WindowAdapter() {
+ public void windowClosing(java.awt.event.WindowEvent e) {
+ System.exit(0);
+ }
+ });
+ dialog.setVisible(true);
+ }
+ });
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JButton jButtonClose;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JLabel jLabel2;
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JTextPane jTextPane1;
+ // End of variables declaration//GEN-END:variables
+
+}
diff -U 3 -H -d -r -N -- original_varna_2.0/varna/EmbeddedRNA.java src/varna/EmbeddedRNA.java
--- original_varna_2.0/varna/EmbeddedRNA.java 2008-01-12 01:01:00.000000000 +0100
+++ src/varna/EmbeddedRNA.java 2008-07-27 11:16:04.000000000 +0200
@@ -1,21 +1,20 @@
/*
- VARNA is a Java library for quick automated drawings RNA secondary structure
- Copyright (C) 2007 Yann Ponty
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
+VARNA is a Java library for quick automated drawings RNA secondary structure
+Copyright (C) 2007 Yann Ponty
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
-*/
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+You should have received a copy of the GNU General Public License
+along with this program. If not, see .
+ */
package varna;
import java.io.FileWriter;
@@ -23,429 +22,457 @@
import varna.export.SecStrDrawingProducer;
import varna.export.PSExport;
+import varna.export.SVGExport;
import varna.export.XFIGExport;
public class EmbeddedRNA {
-
- RNASecStr _str;
- Embedding _em;
-
- static int BASE_RADIUS = 10;
- static double LOOP_DISTANCE = 40.0;
- static double BASE_PAIR_DISTANCE = 45.0;
- static double MULTILOOP_DISTANCE = 35.0;
-
-
-
- public EmbeddedRNA()
- {
- _str = new RNASecStr("CAGCUAACG");
- _em = EmbeddedRNA.drawRNASecStr(_str);
- }
- public EmbeddedRNA(RNASecStr s)
- {
- _str = s;
- _em = EmbeddedRNA.drawRNASecStr(s);
- }
+ RNASecStr _str;
+ Embedding _em;
+ static int BASE_RADIUS = 10;
+ static double LOOP_DISTANCE = 40.0;
+ static double BASE_PAIR_DISTANCE = 45.0;
+ static double MULTILOOP_DISTANCE = 35.0;
- public EmbeddedRNA(RNASecStr s, Embedding em)
- {
- _str = s;
- _em = em;
- }
+ public EmbeddedRNA() {
+ _str = new RNASecStr("CAGCUAACG");
+ _em = EmbeddedRNA.drawRNASecStr(_str);
+ }
-
- public EmbeddedRNA(RNASecStr s, RealPoint[] coords)
- {
- Embedding em = new Embedding();
- em._coords = coords;
- _str = s;
- _em = em;
- }
+ public EmbeddedRNA(RNASecStr s) {
+ _str = s;
+ _em = EmbeddedRNA.drawRNASecStr(s);
+ }
-
- public void saveEmbeddedRNADBN(String path, String title)
- {
- try
- {
- FileWriter out = new FileWriter(path);
- if (!title.equals(""))
- {
- out.write("> "+title+"\n");
- }
- out.write(_str._seq);
- out.write('\n');
- String str = "";
- for (int i=0;i<_str._str.length;i++)
- {
- if (_str._str[i]==-1)
- {
- str += '.';
- }
- else
- {
- if (_str._str[i]>i)
- {
- str += '(';
- }
- else
- {
- str += ')';
- }
- }
- }
- out.write(str);
- out.write('\n');
- out.close();
- }
- catch(Exception e)
- {
- System.err.println("Writing is not allowed with current security policy.");
- }
- }
-
- private void saveEmbeddedRNA(String path, String title, int freqNumbers, double scale, SecStrDrawingProducer out)
- {
- try
- {
- out.setScale(scale);
-
- // Computing bounding boxes
- double EPSMargin = 40;
- double minX = Double.MAX_VALUE;
- double maxX = Double.MIN_VALUE;
- double minY = Double.MAX_VALUE;
- double maxY = Double.MIN_VALUE;
- for (int i=0;i<_em._coords.length;i++)
- {
- minX = Math.min(minX, (_em._coords[i].x-BASE_RADIUS-EPSMargin));
- minY = Math.min(minY, -(_em._coords[i].y-BASE_RADIUS-EPSMargin));
- maxX = Math.max(maxX, (_em._coords[i].x+BASE_RADIUS+EPSMargin));
- maxY = Math.max(maxY, -(_em._coords[i].y+BASE_RADIUS+EPSMargin));
- }
-
- // Drawing backbone
- for (int i=1;i<_em._coords.length;i++)
- {
- long x0 = (long)(_em._coords[i-1].x-minX);
- long y0 = -(long)(_em._coords[i-1].y-minY);
- long x1 = (long)(_em._coords[i].x-minX);
- long y1 = -(long)(_em._coords[i].y-minY);
- out.drawLine(x0, y0, x1, y1,1);
- }
+ public EmbeddedRNA(RNASecStr s, Embedding em) {
+ _str = s;
+ _em = em;
+ }
- // Drawing bonds
- for (int i=0;i<_em._coords.length;i++)
- {
- if (_str._str[i]>i)
- {
- double x0 = (_em._coords[i].x-minX);
- double y0 = -(_em._coords[i].y-minY);
- double x1 = (_em._coords[_str._str[i]].x-minX);
- double y1 = -(_em._coords[_str._str[i]].y-minY);
- double dx = x1-x0;
- double dy = y1-y0;
- double norm = Math.sqrt(dx*dx+dy*dy);
- dx /= norm;
- dy /= norm;
- if (_em._style==VARNAPanel.DRAW_MODE_CIRCLE)
- {
- out.drawLine((long)x0, (long)y0, (long)x1, (long)y1,1);
- }
- else if(_em._style==VARNAPanel.DRAW_MODE_RADIATE)
- {
- out.drawLine((long)(x0+1.5*BASE_RADIUS*dx), (long)(y0+1.5*BASE_RADIUS*dy), (long)(x1-1.5*BASE_RADIUS*dx), (long)(y1-1.5*BASE_RADIUS*dy),2);
- }
- }
- }
-
- // Drawing Bases
- long baseFontSize = (long)(1.5*BASE_RADIUS);
- out.setFont(PSExport.FONT_HELVETICA_BOLD,baseFontSize);
- for (int i=0;i<_em._coords.length;i++)
- {
- long x = (long)(_em._coords[i].x-minX);
- long y = -(long)(_em._coords[i].y-minY);
- out.fillCircle(x, y, BASE_RADIUS, 1l,0.95);
- out.drawCircle(x, y, BASE_RADIUS, 1l);
- out.drawText(x, y, ""+_str._seq[i],baseFontSize);
- }
+ public EmbeddedRNA(RNASecStr s, RealPoint[] coords) {
+ Embedding em = new Embedding();
+ em._coords = coords;
+ _str = s;
+ _em = em;
+ }
- // Drawing base numbers
- long numFontSize = (long)(1.5*BASE_RADIUS);
- out.setFont(PSExport.FONT_HELVETICA_BOLD,numFontSize);
+ public void saveEmbeddedRNADBN(String path, String title) {
+ try {
+ FileWriter out = new FileWriter(path);
+ if (!title.equals("")) {
+ out.write("> " + title + "\n");
+ }
+ out.write(_str._seq);
+ out.write('\n');
+ String str = "";
+ for (int i = 0; i < _str._str.length; i++) {
+ if (_str._str[i] == -1) {
+ str += '.';
+ } else {
+ if (_str._str[i] > i) {
+ str += '(';
+ } else {
+ str += ')';
+ }
+ }
+ }
+ out.write(str);
+ out.write('\n');
+ out.close();
+ } catch (Exception e) {
+ System.err.println("Writing is not allowed with current security policy.");
+ }
+ }
- for (int i=0;i<_em._coords.length;i++)
- {
- if ((i==0)||((i+1)%freqNumbers==0))
- {
- double x0 = (_em._coords[i].x-minX);
- double y0 = -(_em._coords[i].y-minY);
- double x1 = (_em._centers[i].x-minX);
- double y1 = -(_em._centers[i].y-minY);
- double dx = x1-x0;
- double dy = y1-y0;
- double norm = Math.sqrt(dx*dx+dy*dy);
- dx /= norm;
- dy /= norm;
- out.drawLine((long)(x0-1.5*BASE_RADIUS*dx), (long)(y0-1.5*BASE_RADIUS*dy), (long)(x0-2.5*BASE_RADIUS*dx), (long)(y0-2.5*BASE_RADIUS*dy),1);
- out.drawText((long)(x0-4*BASE_RADIUS*dx), (long)(y0-4*BASE_RADIUS*dy), ""+(i+1),numFontSize);
- }
- }
-
- FileWriter fout = new FileWriter(path);
- fout.write(out.export());
- fout.close();
- }
+ private void saveEmbeddedRNA(String path, String title, int freqNumbers, int numOffset, double scale, SecStrDrawingProducer out) {
+ try {
+ out.setScale(scale);
- catch(Exception e)
- {
-
- }
- }
-
- public void saveEmbeddedRNAEPS(String path, String title, int freqNumbers)
- {
- PSExport out = new PSExport();
- saveEmbeddedRNA(path,title,freqNumbers,1,out);
- }
-
- public void saveEmbeddedRNAXFIG(String path, String title, int freqNumbers)
- {
- XFIGExport out = new XFIGExport();
- saveEmbeddedRNA(path,title,freqNumbers,20,out);
- }
+ // Computing bounding boxes
+ double EPSMargin = 40;
+ double minX = Double.MAX_VALUE;
+ double maxX = Double.MIN_VALUE;
+ double minY = Double.MAX_VALUE;
+ double maxY = Double.MIN_VALUE;
+ for (int i = 0; i < _em._coords.length; i++) {
+ minX = Math.min(minX, (_em._coords[i].x - BASE_RADIUS - EPSMargin));
+ minY = Math.min(minY, -(_em._coords[i].y - BASE_RADIUS - EPSMargin));
+ maxX = Math.max(maxX, (_em._coords[i].x + BASE_RADIUS + EPSMargin));
+ maxY = Math.max(maxY, -(_em._coords[i].y + BASE_RADIUS + EPSMargin));
+ }
-
- public void loadEmbeddedRNA(String path)
- {
-
- }
-
- public RealRectangle getBBox()
- {
- RealRectangle result = new RealRectangle(11,10,10,10);
- RealPoint[] _coords = _em._coords;
- double minx,maxx,miny,maxy;
- minx = Double.MAX_VALUE;
- miny = Double.MAX_VALUE;
- maxx = Double.MIN_VALUE;
- maxy = Double.MIN_VALUE;
- for (int i=0;i<_coords.length;i++)
- {
- minx = Math.min(_coords[i].x-BASE_RADIUS,minx);
- miny = Math.min(_coords[i].y-BASE_RADIUS,miny);
- maxx = Math.max(_coords[i].x+BASE_RADIUS,maxx);
- maxy = Math.max(_coords[i].y+BASE_RADIUS,maxy);
- }
- result.x = minx;
- result.y = miny;
- result.width = (maxx - minx);
- result.height = (maxy - miny);
- return result;
- }
-
- public int getSize()
- {
- return _str.getSize();
- }
+// out.setBoundingBox( (long) (maxX-minX), (long) (maxY-minY) );
+// out.setBoundingBox( (long) getBBox().width, (long) getBBox().height );
- public RNASecStr getRNASecStr()
- {
- return _str;
- }
+ // Drawing backbone
+ for (int i = 1; i < _em._coords.length; i++) {
+ long x0 = (long) (_em._coords[i - 1].x - minX);
+ long y0 = -(long) (_em._coords[i - 1].y - minY);
+ long x1 = (long) (_em._coords[i].x - minX);
+ long y1 = -(long) (_em._coords[i].y - minY);
+ out.drawLine(x0, y0, x1, y1, 1);
+ }
- public void setCoord(int index, RealPoint p)
- {
- setCoord(index,p.x,p.y);
- }
+ // Drawing bonds
+ for (int i = 0; i < _em._coords.length; i++) {
+ if (_str._str[i] > i) {
+ double x0 = (_em._coords[i].x - minX);
+ double y0 = -(_em._coords[i].y - minY);
+ double x1 = (_em._coords[_str._str[i]].x - minX);
+ double y1 = -(_em._coords[_str._str[i]].y - minY);
+ double dx = x1 - x0;
+ double dy = y1 - y0;
+ double norm = Math.sqrt(dx * dx + dy * dy);
+ dx /= norm;
+ dy /= norm;
+ if (_em._style == VARNAPanel.DRAW_MODE_CIRCLE) {
+ out.drawLine((long) x0, (long) y0, (long) x1, (long) y1, 1);
+ } else if (_em._style == VARNAPanel.DRAW_MODE_RADIATE) {
+ out.drawLine((long) (x0 + 1.5 * BASE_RADIUS * dx), (long) (y0 + 1.5 * BASE_RADIUS * dy), (long) (x1 - 1.5 * BASE_RADIUS * dx), (long) (y1 - 1.5 * BASE_RADIUS * dy), 2);
+ }
+ }
+ }
- public void setCoord(int index, double x, double y)
- {
- if (index<_str.getSize())
- {
- RealPoint[] _coords = _em._coords;
- _coords[index].x = x;
- _coords[index].y = y;
- }
- }
+ // Drawing Bases
+ long baseFontSize = (long) (1.5 * BASE_RADIUS);
+ out.setFont(PSExport.FONT_HELVETICA_BOLD, baseFontSize);
+ for (int i = 0; i < _em._coords.length; i++) {
+ long x = (long) (_em._coords[i].x - minX);
+ long y = -(long) (_em._coords[i].y - minY);
+ out.fillCircle(x, y, BASE_RADIUS, 1l, 0.95);
+ out.drawCircle(x, y, BASE_RADIUS, 1l);
+ out.drawText(x, y, "" + _str._seq[i], baseFontSize);
+ }
- public RealPoint getCoord(int i)
- {
- if (i<_str.getSize())
- {
- RealPoint[] _coords = _em._coords;
- return _coords[i];
- }
- return new RealPoint();
- }
+ // Drawing base numbers
+ long numFontSize = (long) (1.5 * BASE_RADIUS);
+ out.setFont(PSExport.FONT_HELVETICA_BOLD, numFontSize);
- public RealPoint getCenter(int i)
- {
- if (i<_str.getSize())
- {
- RealPoint[] _centers = _em._centers;
- return _centers[i];
- }
- return new RealPoint();
- }
+ for (int i = 0; i < _em._coords.length; i++) {
+ if ((i == 0) || ((i + 1) % freqNumbers == 0)) {
+ double x0 = (_em._coords[i].x - minX);
+ double y0 = -(_em._coords[i].y - minY);
+ double x1 = (_em._centers[i].x - minX);
+ double y1 = -(_em._centers[i].y - minY);
+ double dx = x1 - x0;
+ double dy = y1 - y0;
+ double norm = Math.sqrt(dx * dx + dy * dy);
+ dx /= norm;
+ dy /= norm;
+ out.drawLine((long) (x0 - 1.5 * BASE_RADIUS * dx), (long) (y0 - 1.5 * BASE_RADIUS * dy), (long) (x0 - 2.5 * BASE_RADIUS * dx), (long) (y0 - 2.5 * BASE_RADIUS * dy), 1);
+ out.drawText((long) (x0 - 4 * BASE_RADIUS * dx), (long) (y0 - 4 * BASE_RADIUS * dy), "" + (i + numOffset), numFontSize);
+ }
+ }
- public char getRes(int i)
- {
- if (i<_str.getSize())
- {
- return _str.getRes(i);
- }
- return 'E';
- }
- public int getBP(int i)
- {
- if (i<_str.getSize())
- {
- return _str.getBP(i);
- }
- return -1;
- }
+ FileWriter fout = new FileWriter(path);
+ fout.write(out.export());
+ fout.close();
+ } catch (Exception e) {
+ }
+ }
- public static Embedding drawRNASecStrCircle(RNASecStr s)
- {
- Embedding result = new Embedding();
- RealPoint[] coords = new RealPoint[s.getSize()];
- RealPoint[] centers = new RealPoint[s.getSize()];
- int radius = (int)((3*(coords.length+1)*BASE_RADIUS)/(2*Math.PI));
- for (int i=0;i i) {
+// double x0 = (_em._coords[i].x - minX);
+// double y0 = -(_em._coords[i].y - minY);
+// double x1 = (_em._coords[_str._str[i]].x - minX);
+// double y1 = -(_em._coords[_str._str[i]].y - minY);
+// double dx = x1 - x0;
+// double dy = y1 - y0;
+// double norm = Math.sqrt(dx * dx + dy * dy);
+// dx /= norm;
+// dy /= norm;
+// if (_em._style == VARNAPanel.DRAW_MODE_CIRCLE) {
+// svgExport.drawLine((long) x0, (long) y0, (long) x1, (long) y1, 1);
+// } else if (_em._style == VARNAPanel.DRAW_MODE_RADIATE) {
+// svgExport.drawLine((long) (x0 + 1.5 * BASE_RADIUS * dx), (long) (y0 + 1.5 * BASE_RADIUS * dy), (long) (x1 - 1.5 * BASE_RADIUS * dx), (long) (y1 - 1.5 * BASE_RADIUS * dy), 2);
+// }
+// }
+// }
+//
+// // Drawing Bases
+// long baseFontSize = (long) (1.5 * BASE_RADIUS);
+// svgExport.setFont(PSExport.FONT_HELVETICA_BOLD, baseFontSize);
+// for (int i = 0; i < _em._coords.length; i++) {
+// long x = (long) (_em._coords[i].x - minX);
+// long y = -(long) (_em._coords[i].y - minY);
+//
+// svgExport.fillCircle(x, y, BASE_RADIUS, 1l, 0.95);
+// svgExport.drawCircle(x, y, BASE_RADIUS, 1l);
+// svgExport.drawText(x, y, "" + _str._seq[i], baseFontSize);
+// }
+//
+// // Drawing base numbers
+// long numFontSize = (long) (1.5 * BASE_RADIUS);
+// svgExport.setFont(PSExport.FONT_HELVETICA_BOLD, numFontSize);
+//
+// for (int i = 0; i < _em._coords.length; i++) {
+// if ((i == 0) || ((i + 1) % freqNumbers == 0)) {
+// double x0 = (_em._coords[i].x - minX);
+// double y0 = -(_em._coords[i].y - minY);
+// double x1 = (_em._centers[i].x - minX);
+// double y1 = -(_em._centers[i].y - minY);
+// double dx = x1 - x0;
+// double dy = y1 - y0;
+// double norm = Math.sqrt(dx * dx + dy * dy);
+// dx /= norm;
+// dy /= norm;
+// svgExport.drawLine((long) (x0 - 1.5 * BASE_RADIUS * dx), (long) (y0 - 1.5 * BASE_RADIUS * dy), (long) (x0 - 2.5 * BASE_RADIUS * dx), (long) (y0 - 2.5 * BASE_RADIUS * dy), 1);
+// svgExport.drawText((long) (x0 - 4 * BASE_RADIUS * dx), (long) (y0 - 4 * BASE_RADIUS * dy), "" + (i + numOffset), numFontSize);
+// }
+// }
+//
+//
+// FileWriter fout = new FileWriter(path);
+// fout.write(svgExport.export());
+// fout.close();
+// } catch (Exception e) {
+// }
+//
+ }
+
+// public void saveEmbeddedRNASVG(String path, String title, int freqNumbers) {
+// SVGExport out = new SVGExport();
+// saveEmbeddedRNA(path, title, freqNumbers, 20, out);
+// }
+
+ public void loadEmbeddedRNA(String path) {
+ }
+
+ public RealRectangle getBBox() {
+ RealRectangle result = new RealRectangle(11, 10, 10, 10);
+ RealPoint[] _coords = _em._coords;
+ double minx, maxx, miny, maxy;
+ minx = Double.MAX_VALUE;
+ miny = Double.MAX_VALUE;
+ maxx = Double.MIN_VALUE;
+ maxy = Double.MIN_VALUE;
+ for (int i = 0; i < _coords.length; i++) {
+ minx = Math.min(_coords[i].x - BASE_RADIUS, minx);
+ miny = Math.min(_coords[i].y - BASE_RADIUS, miny);
+ maxx = Math.max(_coords[i].x + BASE_RADIUS, maxx);
+ maxy = Math.max(_coords[i].y + BASE_RADIUS, maxy);
+ }
+ result.x = minx;
+ result.y = miny;
+ result.width = (maxx - minx);
+ result.height = (maxy - miny);
+ return result;
+ }
+
+ public int getSize() {
+ return _str.getSize();
+ }
+
+ public RNASecStr getRNASecStr() {
+ return _str;
+ }
+
+ public void setCoord(int index, RealPoint p) {
+ setCoord(index, p.x, p.y);
+ }
+
+ public void setCoord(int index, double x, double y) {
+ if (index < _str.getSize()) {
+ RealPoint[] _coords = _em._coords;
+ _coords[index].x = x;
+ _coords[index].y = y;
+ }
+ }
+
+ public RealPoint getCoord(int i) {
+ if (i < _str.getSize()) {
+ RealPoint[] _coords = _em._coords;
+ return _coords[i];
+ }
+ return new RealPoint();
+ }
+
+ public RealPoint getCenter(int i) {
+ if (i < _str.getSize()) {
+ RealPoint[] _centers = _em._centers;
+ return _centers[i];
+ }
+ return new RealPoint();
+ }
+
+ public char getRes(int i) {
+ if (i < _str.getSize()) {
+ return _str.getRes(i);
+ }
+ return 'E';
+ }
+
+ public int getBP(int i) {
+ if (i < _str.getSize()) {
+ return _str.getBP(i);
+ }
+ return -1;
+ }
+
+ public static Embedding drawRNASecStrCircle(RNASecStr s) {
+ Embedding result = new Embedding();
+ RealPoint[] coords = new RealPoint[s.getSize()];
+ RealPoint[] centers = new RealPoint[s.getSize()];
+ int radius = (int) ((3 * (coords.length + 1) * BASE_RADIUS) / (2 * Math.PI));
+ for (int i = 0; i < coords.length; i++) {
+ double angle = -((((double) -(i + 1)) * 2.0 * Math.PI) / ((double) (coords.length + 1)) - Math.PI / 2.0);
+ coords[i] = new RealPoint((radius * Math.cos(angle)), (radius * Math.sin(angle)));
+ centers[i] = new RealPoint(0.0, 0.0);
+ }
+ result._coords = coords;
+ result._centers = centers;
+ result._style = VARNAPanel.DRAW_MODE_CIRCLE;
+ return result;
+ }
+
+ private static void drawLoop(int i, int j, double x, double y, double dirAngle, RNASecStr s, RealPoint[] coords, RealPoint[] centers) {
+ if (i >= j) {
+ return;
+ }
+ if (s.getBP(i) == j) {
+ double normalAngle = Math.PI / 2.0;
+ centers[i] = new RealPoint(x, y);
+ centers[j] = new RealPoint(x, y);
+ coords[i].x = (x + BASE_PAIR_DISTANCE * Math.cos(dirAngle - normalAngle) / 2.0);
+ coords[i].y = (y + BASE_PAIR_DISTANCE * Math.sin(dirAngle - normalAngle) / 2.0);
+ coords[j].x = (x + BASE_PAIR_DISTANCE * Math.cos(dirAngle + normalAngle) / 2.0);
+ coords[j].y = (y + BASE_PAIR_DISTANCE * Math.sin(dirAngle + normalAngle) / 2.0);
+ drawLoop(i + 1, j - 1, x + LOOP_DISTANCE * Math.cos(dirAngle),
+ y + LOOP_DISTANCE * Math.sin(dirAngle), dirAngle, s, coords, centers);
+ } else {
+ int k = i;
+ Vector basesMultiLoop = new Vector();
+ Vector helices = new Vector();
+ while (k <= j) {
+ int l = s.getBP(k);
+ if (l > k) {
+ basesMultiLoop.add(new Integer(k));
+ basesMultiLoop.add(new Integer(l));
+ helices.add(new Integer(k));
+ k = l + 1;
+ } else {
+ basesMultiLoop.add(new Integer(k));
+ k++;
+ }
+ }
+ int mlSize = basesMultiLoop.size() + 2;
+ int numHelices = helices.size() + 1;
+ double totalLength = MULTILOOP_DISTANCE * (mlSize - numHelices) + BASE_PAIR_DISTANCE * numHelices;
+ double multiLoopRadius = (totalLength) / (2.0 * Math.PI);
+
+ double centerDist = Math.sqrt(Math.pow(multiLoopRadius, 2) - Math.pow(BASE_PAIR_DISTANCE / 2.0, 2));
+ RealPoint mlCenter = new RealPoint(
+ (x + (centerDist - LOOP_DISTANCE) * Math.cos(dirAngle)),
+ (y + (centerDist - LOOP_DISTANCE) * Math.sin(dirAngle)));
+
+ double angleIncrementML = -2.0 * Math.PI * (MULTILOOP_DISTANCE / totalLength);
+ double angleIncrementBP = -2.0 * Math.PI * (BASE_PAIR_DISTANCE / totalLength);
+ double baseAngle = dirAngle + Math.PI + 0.5 * angleIncrementBP + 1.0 * angleIncrementML;
+ double[] angles = new double[s.getSize()];
+ for (k = basesMultiLoop.size() - 1; k >= 0; k--) {
+ int l = basesMultiLoop.get(k).intValue();
+ centers[l] = mlCenter;
+ angles[l] = baseAngle;
+ coords[l].x = mlCenter.x + multiLoopRadius * Math.cos(baseAngle);
+ coords[l].y = mlCenter.y + multiLoopRadius * Math.sin(baseAngle);
+ if ((s.getBP(l) < l) && (s.getBP(l) != -1)) {
+ baseAngle += angleIncrementBP;
+ } else {
+ baseAngle += angleIncrementML;
+ }
+ }
+ for (k = 0; k < helices.size(); k++) {
+ int m = helices.get(k).intValue();
+ int n = s.getBP(m);
+ double newAngle = (angles[m] + angles[n]) / 2.0;
+ drawLoop(m + 1, n - 1,
+ (LOOP_DISTANCE * Math.cos(newAngle)) + (coords[m].x + coords[n].x) / 2.0,
+ (LOOP_DISTANCE * Math.sin(newAngle)) + (coords[m].y + coords[n].y) / 2.0,
+ newAngle, s, coords, centers);
+
+ }
+ }
+ }
+
+ public static Embedding drawRNASecStr(RNASecStr s) {
+ Embedding result = new Embedding();
+ RealPoint[] coords = new RealPoint[s.getSize()];
+ for (int i = 0; i < coords.length; i++) {
+ coords[i] = new RealPoint(0, 0);
+ }
+ RealPoint[] centers = new RealPoint[s.getSize()];
+ for (int i = 0; i < centers.length; i++) {
+ centers[i] = new RealPoint(0, 0);
+ }
+ double initialAngle = -1.0;
+ EmbeddedRNA.drawLoop(0, s.getSize() - 1, 0, 0, initialAngle, s, coords, centers);
+
+ result._coords = coords;
+ result._centers = centers;
+ result._style = VARNAPanel.DRAW_MODE_RADIATE;
+ return result;
+ }
+
+ public Range getHelix(int i) {
+ if (_str != null) {
+ return _str.getHelix(i);
+ }
+ return new Range(0, 0);
+ }
+
+ public Range getMultiLoop(int i) {
+ if (_str != null) {
+ return _str.getMultiLoop(i);
+ }
+ return new Range(0, 0);
+ }
-
- private static void drawLoop(int i, int j, double x, double y, double dirAngle,RNASecStr s, RealPoint[] coords, RealPoint[] centers)
- {
- if(i>=j)
- {return ;}
- if (s.getBP(i)==j)
- {
- double normalAngle = Math.PI/2.0;
- centers[i] = new RealPoint(x,y);
- centers[j] = new RealPoint(x,y);
- coords[i].x = (x+BASE_PAIR_DISTANCE*Math.cos(dirAngle-normalAngle)/2.0);
- coords[i].y = (y+BASE_PAIR_DISTANCE*Math.sin(dirAngle-normalAngle)/2.0);
- coords[j].x = (x+BASE_PAIR_DISTANCE*Math.cos(dirAngle+normalAngle)/2.0);
- coords[j].y = (y+BASE_PAIR_DISTANCE*Math.sin(dirAngle+normalAngle)/2.0);
- drawLoop(i+1, j-1, x+LOOP_DISTANCE*Math.cos(dirAngle),
- y+LOOP_DISTANCE*Math.sin(dirAngle), dirAngle,s, coords, centers);
- }
- else
- {
- int k = i;
- Vector basesMultiLoop = new Vector();
- Vector helices = new Vector();
- while(k<=j)
- {
- int l = s.getBP(k);
- if (l>k)
- {
- basesMultiLoop.add(new Integer(k));
- basesMultiLoop.add(new Integer(l));
- helices.add(new Integer(k));
- k = l+1;
- }
- else
- {
- basesMultiLoop.add(new Integer(k));
- k++;
- }
- }
- int mlSize = basesMultiLoop.size()+2;
- int numHelices = helices.size()+1;
- double totalLength = MULTILOOP_DISTANCE*(mlSize-numHelices)+BASE_PAIR_DISTANCE*numHelices;
- double multiLoopRadius = (totalLength)/(2.0*Math.PI);
-
- double centerDist = Math.sqrt(Math.pow(multiLoopRadius,2)-Math.pow(BASE_PAIR_DISTANCE/2.0,2));
- RealPoint mlCenter = new RealPoint(
- (x+(centerDist-LOOP_DISTANCE)*Math.cos(dirAngle)),
- (y+(centerDist-LOOP_DISTANCE)*Math.sin(dirAngle)));
-
- double angleIncrementML = -2.0*Math.PI*(MULTILOOP_DISTANCE/totalLength);
- double angleIncrementBP = -2.0*Math.PI*(BASE_PAIR_DISTANCE/totalLength);
- double baseAngle = dirAngle +Math.PI+ 0.5*angleIncrementBP+1.0*angleIncrementML;
- double[] angles = new double[s.getSize()];
- for(k=basesMultiLoop.size()-1;k>=0;k--)
- {
- int l = basesMultiLoop.get(k).intValue();
- centers[l] = mlCenter;
- angles[l] = baseAngle;
- coords[l].x = mlCenter.x + multiLoopRadius*Math.cos(baseAngle);
- coords[l].y = mlCenter.y + multiLoopRadius*Math.sin(baseAngle);
- if ((s.getBP(l).
-*/
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+You should have received a copy of the GNU General Public License
+along with this program. If not, see .
+ */
package varna;
-
import java.io.BufferedReader;
-import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
@@ -28,445 +25,413 @@
import java.util.Stack;
import java.util.Vector;
-
public class RNASecStr {
- char[] _seq;
- int[] _str;
-
- public RNASecStr(char[] seq, int[] str)
- {
- _seq = seq;
- _str = str;
- }
+ char[] _seq;
+ int[] _str;
+ String name;
- public RNASecStr(String seq, int[] str)
- {
- this(seq.toCharArray(),str);
- }
+ public RNASecStr(char[] seq, int[] str) {
+ _seq = seq;
+ _str = str;
+ }
- public RNASecStr(String seq, String str) throws ParseException
- {
- this(seq.toCharArray(),parseStruct(str));
- }
+ public RNASecStr(String seq, int[] str) {
+ this(seq.toCharArray(), str);
+ }
- static int[] parseStruct(String str) throws ParseException
- {
- int[] result = new int[str.length()];
- Stack p = new Stack();
- for (int i=0;i=_str.length))
- { return new Range(index,index);}
- int j = _str[index];
- if(j!=-1)
- {
- int minH = index;
- int maxH = index;
- if (j>index)
- { maxH = j; }
- else
- { minH = j; }
- boolean over = false;
- while (!over)
- {
- if((minH<0)||(maxH>=_str.length))
- {over = true;}
- else
- {
- if (_str[minH]==maxH)
- {minH--;maxH++;}
- else
- {over = true;}
- }
- }
- minH++;
- maxH--;
- return new Range(minH,maxH);
- }
- return new Range(0,0);
- }
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
- public Range getMultiLoop(int index)
- {
- if((index<0)||(index>=_str.length))
- { return new Range(index,index);}
- Range h = getHelix(index);
- int minH = h.begin-1;
- int maxH = h.end+1;
- boolean over = false;
- while (!over)
- {
- if(minH<0)
- {
- over = true;
- minH=0;
- }
- else
- {
- if(_str[minH]==-1)
- {minH--;}
- else if (_str[minH]_str.length-1)
- {
- over = true;
- maxH=_str.length-1;
- }
- else
- {
- if(_str[maxH]==-1)
- {maxH++;}
- else if (_str[maxH]>maxH)
- {maxH = _str[maxH]+1;}
- else
- {over = true;}
- }
- }
- return new Range(minH,maxH);
- }
+ static int[] parseStruct(String str) throws ParseException {
+ int[] result = new int[str.length()];
+ Stack p = new Stack();
+ for (int i = 0; i < str.length(); i++) {
+ char c = str.charAt(i);
+ if (c == '(') {
+ p.push(new Integer(i));
+ } else if (c == '.') {
+ result[i] = -1;
+ } else if (c == ')') {
+ if (p.size() == 0) {
+ throw (new ParseException("Bad secondary structure (DBN format): Unmatched closing parentheses ')'", i + 1));
+ }
+ int j = p.pop().intValue();
+ result[i] = j;
+ result[j] = i;
+ }
+ }
+ if (p.size() != 0) {
+ throw (new ParseException("Bad secondary structure (DBN format): Unmatched closing parentheses ')'", p.pop().intValue() + 1));
+ }
+ return result;
+ }
- public static RNASecStr loadFromFile(String path)
- {
- RNASecStr r = new RNASecStr("ACAGUAGC");
- return r;
- }
-
- public String getStructDBN()
- {
- String result = "";
- for(int i=0;i<_str.length;i++)
- {
- if(_str[i]==-1)
- {
- result += ".";
- }
- else if(_str[i]>i)
- {
- result += "(";
- }
- else
- {
- result += ")";
- }
- }
- return result;
- }
+ public RNASecStr(String seq) {
+ _seq = seq.toCharArray();
+ _str = new int[seq.length()];
+ for (int i = 0; i < seq.length(); i++) {
+ _str[i] = -1;
+ }
+ }
- public String getStructBPSEQ()
- {
- String result = "";
- for(int i=0;i<_str.length;i++)
- {
- result += (i+1)+" "+_seq[i]+" "+(_str[i]+1)+"\n";
- }
- return result;
- }
+ public char getRes(int i) {
+ if (i < _seq.length) {
+ return _seq[i];
+ }
+ return 'E';
+ }
- public String getStructCT()
- {
- String result = "";
- for(int i=0;i<_str.length;i++)
- {
- result += (i+1)+" "+_seq[i]+" "+i+" "+(i+2)+" "+(_str[i]+1)+" "+(i+1)+"\n";
- }
- return result;
- }
+ public int getSize() {
+ return _seq.length;
+ }
- public void exportBPSEQ(String path, String title)
- {
- try
- {
- FileWriter f = new FileWriter(path);
- f.write("# "+title+"\n");
- f.write(this.getStructBPSEQ()+"\n");
- f.close();
- }
- catch(IOException e)
- {
- System.err.println("Export failed!\n File '"+path+"' cannot be created or overwritten !");
- }
- catch(Exception egen)
- {
- System.err.println("Permission denied for security reason !\nConsider using the VARNA panel class in a signed context.");
- }
- }
+ public int getBP(int i) {
+ if (i < _seq.length) {
+ return _str[i];
+ }
+ return -1;
+ }
+ /**
+ * Get range of helix(hairpin) to which base at given index belongs.
+ * @param index
+ * @return
+ */
+ public Range getHelix(int index) {
+ if ((index < 0) || (index >= _str.length)) {
+ return new Range(index, index);
+ }
+ int j = _str[index];
+ if (j != -1) {
+ int minH = index;
+ int maxH = index;
+ if (j > index) {
+ maxH = j;
+ } else {
+ minH = j;
+ }
+ boolean over = false;
+ while (!over) {
+ if ((minH < 0) || (maxH >= _str.length)) {
+ over = true;
+ } else {
+ if (_str[minH] == maxH) {
+ minH--;
+ maxH++;
+ } else {
+ over = true;
+ }
+ }
+ }
+ minH++;
+ maxH--;
+ return new Range(minH, maxH);
+ }
+ return new Range(0, 0);
+ }
+ /**
+ * Get range of multiloop to which current base is based.
+ * @param index
+ * @return
+ */
+ public Range getMultiLoop(int index) {
+ if ((index < 0) || (index >= _str.length)) {
+ return new Range(index, index);
+ }
+ Range h = getHelix(index);
+ int minH = h.begin - 1;
+ int maxH = h.end + 1;
+ boolean over = false;
+ while (!over) {
+ if (minH < 0) {
+ over = true;
+ minH = 0;
+ } else {
+ if (_str[minH] == -1) {
+ minH--;
+ } else if (_str[minH] < minH) {
+ minH = _str[minH] - 1;
+ } else {
+ over = true;
+ }
+ }
+ }
+ over = false;
+ while (!over) {
+ if (maxH > _str.length - 1) {
+ over = true;
+ maxH = _str.length - 1;
+ } else {
+ if (_str[maxH] == -1) {
+ maxH++;
+ } else if (_str[maxH] > maxH) {
+ maxH = _str[maxH] + 1;
+ } else {
+ over = true;
+ }
+ }
+ }
+ return new Range(minH, maxH);
+ }
- public void exportCT(String path, String title)
- {
- try
- {
- FileWriter f = new FileWriter(path);
- f.write(""+_seq.length+" "+title+"\n");
- f.write(this.getStructCT()+"\n");
- f.close();
- }
- catch(IOException e)
- {
- System.err.println("Export failed!\n File '"+path+"' cannot be created or overwritten !");
- }
- catch(Exception egen)
- {
- System.err.println("Permission denied for security reason !\nConsider using the VARNA panel class in a signed context.");
- }
- }
+ public static RNASecStr loadFromFile(String path) {
+ RNASecStr r = new RNASecStr("ACAGUAGC");
+ return r;
+ }
- public void exportDBN(String path, String title)
- {
- try
- {
- FileWriter f = new FileWriter(path);
- f.write("> "+title+"\n");
- f.write(new String(_seq) + "\n");
- f.write(getStructDBN()+"\n");
- f.close();
- }
- catch(IOException e)
- {
- System.err.println("Export failed!\n File '"+path+"' cannot be created or overwritten !");
- }
- catch(Exception egen)
- {
- System.err.println("Permission denied for security reason !\nConsider using the VARNA panel class in a signed context.");
- }
- }
-
- public static RNASecStr loadSecStrBPSEQ(String path)
- {
- RNASecStr res = null;
- try
- {
- BufferedReader fr = new BufferedReader(new FileReader(path));
- String line = fr.readLine();
- String seqTmp = "";
- Vector strTmp = new Vector();
- while(line!= null)
- {
- line = line.trim();
- String[] tokens = line.split("\\s+");
- if (tokens.length==3)
- {
- try
- {
- int bpFrom = (Integer.parseInt(tokens[0]))-1;
- char base = tokens[1].charAt(tokens[1].length()-1);
- int bpTo = (Integer.parseInt(tokens[2]))-1;
- if (bpFrom!=seqTmp.length())
- {
- System.err.println("Discontinuity detected between nucleotides "+(seqTmp.length())+" and "+(bpFrom+1)+"!");
- System.err.println("Filling in missing portions with unpaired unknown 'X' nucleotides ...");
- while(bpFrom!=seqTmp.length())
- {
- seqTmp += 'X';
- strTmp.add(-1);
- }
- }
- seqTmp += base;
- strTmp.add(bpTo);
- }
- catch(Exception e3)
- { }
- }
- line = fr.readLine();
- }
- if (strTmp.size()!=0)
- {
- char[] seq = seqTmp.toCharArray();
- int[] str = new int[strTmp.size()];
- for(int i=0;i i) {
+ result += "(";
+ } else {
+ result += ")";
+ }
+ }
+ return result;
+ }
- public static RNASecStr loadSecStrCT(String path)
- {
- RNASecStr res = null;
- try
- {
- BufferedReader fr = new BufferedReader(new FileReader(path));
- String line = fr.readLine();
- String seqTmp = "";
- Vector strTmp = new Vector();
- while(line!= null)
- {
- line = line.trim();
- String[] tokens = line.split("\\s+");
- if (tokens.length>=6)
- {
- try
- {
- int bpFrom = (Integer.parseInt(tokens[0]))-1;
- char base = tokens[1].charAt(tokens[1].length()-1);
- int bpTo = (Integer.parseInt(tokens[4]))-1;
- Integer.parseInt(tokens[2]);
- Integer.parseInt(tokens[3]);
- Integer.parseInt(tokens[5]);
- System.err.print("("+bpFrom+","+base+","+bpTo+")");
- if (bpFrom!=seqTmp.length())
- {
- System.err.println("Discontinuity detected between nucleotides "+(seqTmp.length())+" and "+(bpFrom+1)+"!");
- System.err.println("Filling in missing portions with unpaired unknown 'X' nucleotides ...");
- while(bpFrom!=seqTmp.length())
- {
- seqTmp += 'X';
- strTmp.add(-1);
- }
- }
- seqTmp += base;
- strTmp.add(bpTo);
- }
- catch(Exception e3)
- {}
- }
- line = fr.readLine();
- }
- if (strTmp.size()!=0)
- {
- char[] seq = seqTmp.toCharArray();
- int[] str = new int[strTmp.size()];
- for(int i=0;i"))
- {
- if (seqTmp.equals(""))
- { seqTmp = line; }
- else
- { strTmp = line; }
- }
- line = fr.readLine();
- }
- if (strTmp.length()!=0)
- { return new RNASecStr(seqTmp,strTmp); }
- }
- catch(IOException e)
- { System.err.println("Loading failed!\n File '"+path+"' cannot be read !"); }
- catch(ParseException e)
- { System.err.println("Unbalanced parentheses expression, cannot resolve secondary structure."); }
- catch(Exception egen)
- { System.err.println("Permission denied for security reason !\nConsider using the VARNA panel class in a signed context."); }
- return null;
- }
-
- public static RNASecStr loadSecStr(String path)
- {
- RNASecStr s = null;
- s = loadSecStrCT(path);
- if (s != null)
- {
- System.err.println("CT format detected for file '"+path+"'. \nStructure successfully loaded !");
- return s;
- }
- else System.err.println("Not in CT format.");
-
- s = loadSecStrBPSEQ(path);
- if (s != null)
- {
- System.err.println("BPSEQ format detected for file '"+path+"'. \nStructure successfully loaded !");
- return s;
- }
- else System.err.println("Not in BPSEQ format.");
- s = loadSecStrDBN(path);
- if (s != null)
- {
- System.err.println("DBN format detected for file '"+path+"'. \nStructure successfully loaded !");
- return s;
- }
- else System.err.println("Not in DBN format.");
- System.err.println("Unknown format or syntax error in file '"+path+"'. \nLoading cancelled !");
- return s;
- }
-
+ public String getStructCT() {
+ String result = "";
+ for (int i = 0; i < _str.length; i++) {
+ result += (i + 1) + " " + _seq[i] + " " + i + " " + (i + 2) + " " + (_str[i] + 1) + " " + (i + 1) + "\n";
+ }
+ return result;
+ }
+
+ public void exportBPSEQ(String path, String title) {
+ try {
+ FileWriter f = new FileWriter(path);
+ f.write("# " + title + "\n");
+ f.write(this.getStructBPSEQ() + "\n");
+ f.close();
+ } catch (IOException e) {
+ System.err.println("Export failed!\n File '" + path + "' cannot be created or overwritten !");
+ } catch (Exception egen) {
+ System.err.println("Permission denied for security reason !\nConsider using the VARNA panel class in a signed context.");
+ }
+ }
+
+ public void exportCT(String path, String title) {
+ try {
+ FileWriter f = new FileWriter(path);
+ f.write("" + _seq.length + " " + title + "\n");
+ f.write(this.getStructCT() + "\n");
+ f.close();
+ } catch (IOException e) {
+ System.err.println("Export failed!\n File '" + path + "' cannot be created or overwritten !");
+ } catch (Exception egen) {
+ System.err.println("Permission denied for security reason !\nConsider using the VARNA panel class in a signed context.");
+ }
+ }
+
+ public void exportDBN(String path, String title, Range helix) {
+ try {
+ FileWriter f = new FileWriter(path);
+ f.write("> " + title + "\n");
+ f.write(new String(_seq).substring(helix.begin, helix.end + 1) + "\n");
+ f.write(getStructDBN().substring(helix.begin, helix.end + 1) + "\n");
+ f.close();
+ } catch (IOException e) {
+ System.err.println("Export failed!\n File '" + path + "' cannot be created or overwritten !");
+ } catch (Exception egen) {
+ System.err.println("Permission denied for security reason !\nConsider using the VARNA panel class in a signed context.");
+ }
+ }
+
+ public void exportDBN(String path, String title) {
+ try {
+ FileWriter f = new FileWriter(path);
+ f.write("> " + title + "\n");
+ f.write(new String(_seq) + "\n");
+ f.write(getStructDBN() + "\n");
+ f.close();
+ } catch (IOException e) {
+ System.err.println("Export failed!\n File '" + path + "' cannot be created or overwritten !");
+ } catch (Exception egen) {
+ System.err.println("Permission denied for security reason !\nConsider using the VARNA panel class in a signed context.");
+ }
+ }
+
+ public static RNASecStr loadSecStrBPSEQ(String path) {
+ RNASecStr res = null;
+ try {
+ BufferedReader fr = new BufferedReader(new FileReader(path));
+ String line = fr.readLine();
+ String seqTmp = "";
+ Vector strTmp = new Vector();
+ while (line != null) {
+ line = line.trim();
+ String[] tokens = line.split("\\s+");
+ if (tokens.length == 3) {
+ try {
+ int bpFrom = (Integer.parseInt(tokens[0])) - 1;
+ char base = tokens[1].charAt(tokens[1].length() - 1);
+ int bpTo = (Integer.parseInt(tokens[2])) - 1;
+ if (bpFrom != seqTmp.length()) {
+ System.err.println("Discontinuity detected between nucleotides " + (seqTmp.length()) + " and " + (bpFrom + 1) + "!");
+ System.err.println("Filling in missing portions with unpaired unknown 'X' nucleotides ...");
+ while (bpFrom != seqTmp.length()) {
+ seqTmp += 'X';
+ strTmp.add(-1);
+ }
+ }
+ seqTmp += base;
+ strTmp.add(bpTo);
+ } catch (Exception e3) {
+ }
+ }
+ line = fr.readLine();
+ }
+ if (strTmp.size() != 0) {
+ char[] seq = seqTmp.toCharArray();
+ int[] str = new int[strTmp.size()];
+ for (int i = 0; i < strTmp.size(); i++) {
+ str[i] = strTmp.elementAt(i).intValue();
+ }
+ res = new RNASecStr(seq, str);
+ }
+ } catch (IOException e) {
+ System.err.println("Loading failed!\n File '" + path + "' cannot be read !");
+ } catch (Exception egen) {
+ System.err.println("Permission denied for security reason !\nConsider using the VARNA panel class in a signed context.");
+ }
+ return res;
+ }
+
+ public static RNASecStr loadSecStrCT(String path) {
+ RNASecStr res = null;
+ try {
+ BufferedReader fr = new BufferedReader(new FileReader(path));
+ String line = fr.readLine();
+ String seqTmp = "";
+ Vector strTmp = new Vector();
+ while (line != null) {
+ line = line.trim();
+ String[] tokens = line.split("\\s+");
+ if (tokens.length >= 6) {
+ try {
+ int bpFrom = (Integer.parseInt(tokens[0])) - 1;
+ char base = tokens[1].charAt(tokens[1].length() - 1);
+ int bpTo = (Integer.parseInt(tokens[4])) - 1;
+ Integer.parseInt(tokens[2]);
+ Integer.parseInt(tokens[3]);
+ Integer.parseInt(tokens[5]);
+ System.err.print("(" + bpFrom + "," + base + "," + bpTo + ")");
+ if (bpFrom != seqTmp.length()) {
+ System.err.println("Discontinuity detected between nucleotides " + (seqTmp.length()) + " and " + (bpFrom + 1) + "!");
+ System.err.println("Filling in missing portions with unpaired unknown 'X' nucleotides ...");
+ while (bpFrom != seqTmp.length()) {
+ seqTmp += 'X';
+ strTmp.add(-1);
+ }
+ }
+ seqTmp += base;
+ strTmp.add(bpTo);
+ } catch (Exception e3) {
+ }
+ }
+ line = fr.readLine();
+ }
+ if (strTmp.size() != 0) {
+ char[] seq = seqTmp.toCharArray();
+ int[] str = new int[strTmp.size()];
+ for (int i = 0; i < strTmp.size(); i++) {
+ str[i] = strTmp.elementAt(i).intValue();
+ }
+ res = new RNASecStr(seq, str);
+ }
+ } catch (IOException e) {
+ System.err.println("Loading failed!\n File '" + path + "' cannot be read !");
+ } catch (Exception egen) {
+ System.err.println("Permission denied for security reason !\nConsider using the VARNA panel class in a signed context.");
+ }
+ return res;
+ }
+
+ public static RNASecStr loadSecStrDBN(String path) {
+ try {
+ BufferedReader fr = new BufferedReader(new FileReader(path));
+ String line = fr.readLine();
+ String seqTmp = "";
+ String strTmp = "";
+ while ((line != null) && (strTmp.equals(""))) {
+ line = line.trim();
+ if (!line.startsWith(">")) {
+ if (seqTmp.equals("")) {
+ seqTmp = line;
+ } else {
+ strTmp = line;
+ }
+ }
+ line = fr.readLine();
+ }
+ if (strTmp.length() != 0) {
+ return new RNASecStr(seqTmp, strTmp);
+ }
+ } catch (IOException e) {
+ System.err.println("Loading failed!\n File '" + path + "' cannot be read !");
+ } catch (ParseException e) {
+ System.err.println("Unbalanced parentheses expression, cannot resolve secondary structure.");
+ } catch (Exception egen) {
+ System.err.println("Permission denied for security reason !\nConsider using the VARNA panel class in a signed context.");
+ }
+ return null;
+ }
+
+ public static RNASecStr loadSecStr(String path) {
+ RNASecStr s = null;
+ s = loadSecStrCT(path);
+ if (s != null) {
+ System.err.println("CT format detected for file '" + path + "'. \nStructure successfully loaded !");
+ return s;
+ } else {
+ System.err.println("Not in CT format.");
+ }
+ s = loadSecStrBPSEQ(path);
+ if (s != null) {
+ System.err.println("BPSEQ format detected for file '" + path + "'. \nStructure successfully loaded !");
+ return s;
+ } else {
+ System.err.println("Not in BPSEQ format.");
+ }
+ s = loadSecStrDBN(path);
+ if (s != null) {
+ System.err.println("DBN format detected for file '" + path + "'. \nStructure successfully loaded !");
+ return s;
+ } else {
+ System.err.println("Not in DBN format.");
+ }
+ System.err.println("Unknown format or syntax error in file '" + path + "'. \nLoading cancelled !");
+ return s;
+ }
}
diff -U 3 -H -d -r -N -- original_varna_2.0/varna/Range.java src/varna/Range.java
--- original_varna_2.0/varna/Range.java 2007-10-09 22:26:00.000000000 +0200
+++ src/varna/Range.java 2008-03-25 23:48:23.000000000 +0100
@@ -32,9 +32,40 @@
end = j;
}
+ public boolean contains(int i) {
+ return (begin <= i) && (i <= end);
+ }
+
public String toString()
{
return "["+begin+","+end+"]";
}
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ final Range other = (Range) obj;
+ if (this.begin != other.begin) {
+ return false;
+ }
+ if (this.end != other.end) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 7;
+ hash = 11 * hash + this.begin;
+ hash = 11 * hash + this.end;
+ return hash;
+ }
+
}
diff -U 3 -H -d -r -N -- original_varna_2.0/varna/RealPoint.java src/varna/RealPoint.java
--- original_varna_2.0/varna/RealPoint.java 2007-10-09 22:26:00.000000000 +0200
+++ src/varna/RealPoint.java 2008-03-25 22:34:44.000000000 +0100
@@ -44,9 +44,15 @@
y = _y;
}
+ public void add(RealPoint p) {
+ x += p.x;
+ y += p.y;
+ }
+
public double distance(RealPoint p)
{ return Math.sqrt(Math.pow(x-p.x, 2)+Math.pow(y-p.y, 2));}
+ @Override
public String toString()
{
return "("+x+","+y+")";
diff -U 3 -H -d -r -N -- original_varna_2.0/varna/RealRectangle.java src/varna/RealRectangle.java
--- original_varna_2.0/varna/RealRectangle.java 2007-10-09 22:27:00.000000000 +0200
+++ src/varna/RealRectangle.java 2008-03-24 15:08:47.000000000 +0100
@@ -33,5 +33,12 @@
width = w0;
height = h0;
}
+
+ @Override
+ public String toString() {
+ return "[" + x + ", " + y + ", " + width + ", " + height + "]";
+ }
+
+
}
diff -U 3 -H -d -r -N -- original_varna_2.0/varna/VARNAPanel.form src/varna/VARNAPanel.form
--- original_varna_2.0/varna/VARNAPanel.form 1970-01-01 01:00:00.000000000 +0100
+++ src/varna/VARNAPanel.form 2008-09-04 18:03:09.000000000 +0200
@@ -0,0 +1,43 @@
+
+
+
diff -U 3 -H -d -r -N -- original_varna_2.0/varna/VARNAPanel.java src/varna/VARNAPanel.java
--- original_varna_2.0/varna/VARNAPanel.java 2008-01-12 00:57:00.000000000 +0100
+++ src/varna/VARNAPanel.java 2008-09-11 19:39:25.000000000 +0200
@@ -1,1411 +1,1732 @@
-/*
- VARNA is a Java library for quick automated drawings RNA secondary structure
- Copyright (C) 2007 Yann Ponty
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
-*/
-package varna;
-
-
-import java.awt.*;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.awt.event.MouseEvent;
-import java.awt.event.MouseListener;
-import java.awt.event.MouseMotionListener;
-import java.awt.geom.*;
-import java.awt.image.BufferedImage;
-import java.io.FileOutputStream;
-import java.io.OutputStream;
-import java.text.ParseException;
-import java.util.Vector;
-
-import javax.swing.*;
-
-import com.sun.image.codec.jpeg.JPEGCodec;
-import com.sun.image.codec.jpeg.JPEGImageEncoder;
-
-/**
- * The RNA 2D Panel is a lightweight component that allows for
- * an automatic basic drawing of an RNA secondary structures.
- * The drawing algorithms do not ensure a non-overlapping drawing
- * of helices, thus it is possible to "spin the helices" through a
- * click-and-drag approach. A typical usage of the class from within
- * the constructor of a JFrame
would be the following:
- *
- * RNAPanel _rna = new RNAPanel("CCCCAUAUGGGGACC","((((....))))...");
- * this.getContentPane().add(_rna);
- *
- * @version 1.0
- * @author Yann Ponty
- *
- */
-
-
-public class VARNAPanel extends JPanel {
-
- private static final long serialVersionUID = 1L;
-
- static final int DRAW_MODE_UNKNOWN = -1;
- /**
- * Selects the "Feynman diagram" drawing algorithm that places
- * the bases on a circle and draws the base-pairings as chords
- * of the circle graph.
- */
- public static final int DRAW_MODE_CIRCLE = 1;
- /**
- * Selects the "tree drawing" algorithm. Draws
- * each loop on a circle whose radius depends on the number of bases involved
- * in the loop. As some helices can be overlapping in the result, basic
- * interaction is provided so that the user can "disentangle" the drawing
- * by spinning the helices around the axis defined by their multiloop
- * (bulge or internal loop) origin. This is roughly the initial placement
- * strategy of RNAViz.
- * @see RNAViz
- */
- public static final int DRAW_MODE_RADIATE = 2;
-
-
- private int BORDER = 15;
- private EmbeddedRNA _r = new EmbeddedRNA();
- private Color BACKBONE_COLOR = Color.black;
- private Color BOND_COLOR = Color.blue;
- private Color BASE_OUTLINE_COLOR = Color.DARK_GRAY;
- private Color BASE_INNER_COLOR = new Color(230,230,230);
- private Color BASE_NUMBERS_COLOR = Color.DARK_GRAY;
- private Color BASE_NAME_COLOR = Color.black;
- private Color TITLE_COLOR = Color.black;
- private int TITLE_HEIGHT = 30;
- private int _numPeriod = 5;
- private boolean _autoFit = true;
- private boolean _autoCenter = true;
- private Font _titleFont;
- private String _title="";
- private String _titleFontFamily="Arial";
- private String _titleFontStyle="PLAIN";
- private int _titleFontSize=18;
- private String _baseFontFamily="Arial";
- private String _baseFontStyle="BOLD";
- private int _baseFontSize=18;
- private Font _baseNameFont;
- private int _drawMode = DRAW_MODE_UNKNOWN;
-
-
- private BasicStroke dashed;
- private RealPoint[] _realCoords=new RealPoint[0];
- private int _selectedBase = -1;
- private double _scaleFactor = 1.0;
- private RealPoint _offsetPanel = new RealPoint();
- private RealPoint _offsetRNA = new RealPoint();
-
-
- /**
- * Creates an RNA 2D panel with initially displays the empty structure.
- */
- public VARNAPanel()
- {
- this("","",DRAW_MODE_RADIATE);
- }
-
- /**
- * Creates an RNA 2D panel, and creates and displays an RNA coupled
- * with its secondary structure formatted as a well-balanced parenthesis
- * with dots word (DBN format).
- * @param seq The raw nucleotide sequence
- * @param str The secondary structure in DBN format
- */
- public VARNAPanel(String seq, String str)
- {
- this(seq,str,DRAW_MODE_RADIATE);
- }
-
- /**
- * Creates an RNA 2D panel, and creates and displays an RNA coupled
- * with its secondary structure formatted as a well-balanced parenthesis
- * with dots word (DBN format). Allows the user to choose the drawing
- * algorithm to be used.
- * @param seq The raw nucleotide sequence
- * @param str The secondary structure in DBN format
- * @param drawMode The drawing mode
- * @see #DRAW_MODE_CIRCLE
- * @see #DRAW_MODE_RADIATE
- */
- public VARNAPanel(String seq, String str,int drawMode)
- {
- this(seq,str,drawMode,"");
- }
-
- /**
- * Creates an RNA 2D panel, and creates and displays an RNA coupled
- * with its secondary structure formatted as a well-balanced parenthesis
- * with dots word (DBN format). Allows the user to choose the drawing
- * algorithm to be used. Additionally, sets the panel's title.
- * @param seq The raw nucleotide sequence
- * @param str The secondary structure in DBN format
- * @param drawMode The drawing mode
- * @param title The panel title
- * @see #DRAW_MODE_CIRCLE
- * @see #DRAW_MODE_RADIATE
- */
- public VARNAPanel(String seq, String str,int drawMode,String title)
- {
- super();
- _title = title;
- _drawMode = drawMode;
- setRNA(seq,str);
- init();
- }
-
- JPopupMenu popup= new JPopupMenu();
-
- private void init()
- {
- float[] ds = new float[2];
- ds[0] = 5.0f;
- ds[1] = 5.0f;
- dashed = new BasicStroke(2.0f,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND,3.0f,ds,0.0f);
- this.setBackground(Color.white);
- GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
- Font[] avlFonts = ge.getAllFonts();
-
- _baseNameFont = Font.decode(""+_baseFontFamily+"-"+_baseFontStyle+"-"+_baseFontSize);
- _titleFont = Font.decode(""+_titleFontFamily+"-"+_titleFontStyle+"-"+_titleFontSize);
- this.setFont(_baseNameFont);
-
- buildPopupMenu();
-
- this.addMouseListener(new MouseListener(){
- public void mouseClicked(MouseEvent arg0) {}
- public void mouseEntered(MouseEvent arg0) {}
- public void mouseExited(MouseEvent arg0) {}
- public void mousePressed(MouseEvent arg0)
- {onMousePressed(arg0);}
- public void mouseReleased(MouseEvent arg0) {}});
- this.addMouseMotionListener(new MouseMotionListener(){
- public void mouseDragged(MouseEvent me) {
- if(_selectedBase!=-1)
- {
- if (_drawMode == VARNAPanel.DRAW_MODE_CIRCLE)
- {
- moveSingleAtom(_selectedBase, me.getX(),me.getY());
- }
- else
- {
- moveHelixAtom(_selectedBase, me.getX(),me.getY());
- }
- }
- }
- public void mouseMoved(MouseEvent arg0) {
- }});
- }
-
-
- public void onMousePressed(MouseEvent arg0)
- {
- if (arg0.getButton()==1)
- {
- // TODO Auto-generated method stub
- if (_realCoords != null)
- {
- double dist=Double.MAX_VALUE;
- for(int i=0;i<_realCoords.length;i++)
- {
- double d2 =Math.sqrt(Math.pow((_realCoords[i].x-arg0.getX()),2)
- + Math.pow((_realCoords[i].y-arg0.getY()),2));
- if((dist>d2)&&(_r._str.getBP(i)!=-1))
- {
- _selectedBase = i;
- dist = d2;
- }
- }
- //System.out.println("[1]"+_selectedBase);
- }
- }
- else
- {
- _selectedBase = -1;
- popup.show(this,arg0.getX(),arg0.getY());
- }
- }
-
- void reset()
- {
- setRNA(_r._str,_drawMode);
- }
-
-
-
- /**
- * Sets the RNA secondary structure to be drawn in this panel, using the default layout algorithm.
- * In addition to the raw nucleotides sequence, the secondary structure is given
- * in the so-called "Dot-bracket notation" (DBN) format.
- * This format is a well-parenthesized word over the alphabet '(',')','.'.
- * Ex: ((((((((....))))..(((((...))).))))))
- * Returns true
if the sequence/structure couple could be parsed into a
- * valid secondary structure, and false
otherwise.
- * @param seq The raw nucleotides sequence
- * @param str The secondary structure
- * @return true
if the sequence/structure couple could be parsed into a
- * valid secondary structure, false
otherwise
- */
- public boolean setRNA(String seq, String str)
- {
- return setRNA(seq,str,_drawMode);
- }
-
- /**
- * Sets the RNA secondary structure to be drawn in this panel, using a given layout algorithm.
- * @param r The new secondary structure
- * @param drawMode The drawing algorithm
- */
- public void setRNA(RNASecStr r, int drawMode)
- {
- _drawMode=drawMode;
- setRNA(r);
- }
-
-
- /**
- * Sets the RNA secondary structure to be drawn in this panel, using the current drawing algorithm.
- * @param r The new secondary structure
- */
- public void setRNA(RNASecStr r)
- {
- if (r!=null)
- {
- Embedding coords;
- switch(_drawMode)
- {
- case DRAW_MODE_RADIATE:
- coords = EmbeddedRNA.drawRNASecStr(r);
- break;
- case DRAW_MODE_CIRCLE:
- coords = EmbeddedRNA.drawRNASecStrCircle(r);
- break;
- default :
- coords = new Embedding();
- break;
- }
- _r = new EmbeddedRNA(r,coords);
- }
- }
-
- /**
- * Sets the RNA secondary structure to be drawn in this panel, using a given layout algorithm.
- * In addition to the raw nucleotides sequence, the secondary structure is given
- * in the so-called "Dot-bracket notation" (DBN) format.
- * This format is a well-parenthesized word over the alphabet '(',')','.'.
- * Ex: ((((((((....))))..(((((...))).))))))
- * Returns true
if the sequence/structure couple could be parsed into a
- * valid secondary structure, and false
otherwise.
- * @param seq The raw nucleotides sequence
- * @param str The secondary structure
- * @param drawMode The drawing algorithm
- * @return true
if the sequence/structure couple could be parsed into a
- * valid secondary structure, false
otherwise
- */
- public boolean setRNA(String seq, String str, int drawMode)
- {
- _drawMode=drawMode;
- if (seq.length()!=str.length())
- {
- System.err.println("Sequence length "+seq.length()+" differs from that of secondary structure "+str.length()+". \nAdapting sequence length ...");
- if (seq.length()i)
- {g2.drawLine((int)newCoords[i].x, (int)newCoords[i].y, (int)newCoords[j].x, (int)newCoords[j].y);}
- }
-
-
- // Drawing bases
- g2.setStroke(plain);
- g2.setFont(_baseNameFont);
- for(int i=0;i<_r.getSize();i++)
- {
- char c = _r.getRes(i);
- drawBase(g2,i,c,newCoords[i],newCenters[i],newRadius);
- }
-
- // Drawing bbox
- //g2.setColor(Color.GRAY);
- //g2.setStroke(dashed);
- //g2.drawRect(offX, offY, newWidth, newHeight);
- }
-
-
-
- public void paintComponent(Graphics g2)
- {
- super.paintComponent(g2);
- Graphics2D g = (Graphics2D) g2;
- g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON );
- g.setColor(getBackground());
- g.fillRect(0, 0, this.getWidth(), this.getHeight());
-
-
- g.setColor(TITLE_COLOR);
- int width = this.getWidth();
- int height = this.getHeight();
- if (!_title.equals(""))
- {
- g2.setFont(_titleFont);
- drawStringCentered(g,_title,width/2,height-TITLE_HEIGHT/2.0);
- height -= TITLE_HEIGHT;
- }
- int innerWidth=width-2*BORDER;
- int innerHeight=height-2*BORDER;
- int leftOffset=BORDER+((width-2*BORDER)-innerWidth)/2;
- int topOffset=BORDER+((height-2*BORDER)-innerHeight)/2;
-
-
- // Display outer rectangle
- g.setColor(Color.GRAY);
- g.setStroke(dashed);
- //g.drawRect(leftOffset, topOffset, innerWidth, innerHeight);
-
- // Draw RNA
- renderRNA(g,new RealRectangle(leftOffset,topOffset,innerWidth,innerHeight));
- }
-
- private RealPoint panelToLogicPoint(RealPoint p)
- {
- return new RealPoint(((p.x-_offsetPanel.x)/_scaleFactor)+_offsetRNA.x,
- ((p.y-_offsetPanel.y)/_scaleFactor)+_offsetRNA.y);
- }
-
- private void moveSingleAtom(int index, int x, int y)
- {
- if((index>=0)&&(index<_r.getSize()))
- {
- RealPoint pr = _realCoords[index];
- RealPoint pold = _r.getCoord(index);
- double dx = ((x-pr.x)/_scaleFactor);
- double dy = ((y-pr.y)/_scaleFactor);
-
- _r.setCoord(index, pold.x+dx,pold.y+dy);
- this.repaint();
- }
- }
-
- private void moveHelixAtom(int index, int x, int y)
- {
- if((index>=0)&&(index<_r.getSize()))
- {
- RNASecStr r = _r.getRNASecStr();
- int indexTo = r.getBP(index);
- if(indexTo!=-1)
- {
- Range h = _r.getHelix(index);
- Range ml = _r.getMultiLoop(h.begin);
-
- int i = ml.begin;
- if((ml.begin==0)||(ml.end==_r.getSize()-1))
- {return ;}
- int prevIndex = h.begin;
- int nextIndex = h.end;
- while(i<=ml.end)
- {
- int j = _r.getBP(i);
- if((j!=-1)&&(ih.end)&&(nextIndex==h.end))
- {
- nextIndex = i;
- }
- if((j>i)&&(j %.2f < %.2f < [%.2f,%.2f] < %.2f < %.2f\n",base, pLimR,pHelR,pNew,pOld,pHelL,pLimL);
- if(pLimR<0.0) pLimR += 2.0*Math.PI;
- if((pHelR<0.0)||(pHelR %.2f < %.2f < [%.2f,%.2f] < %.2f < %.2f\n",base, pLimR,pHelR,pNew,pOld,pHelL,pLimL);
-
- double minDelta = (normalizeAngle(pHelR)-normalizeAngle(pLimR));
- double maxDelta = normalizeAngle(pLimL)-normalizeAngle(pHelL);
- //double maxDelta = 300;
-
- double delta = normalizeAngle(pNew)-normalizeAngle(pOld);
-
-
- delta = Math.max(-minDelta+0.25,delta);
- delta = Math.min(maxDelta-0.25,delta);
- rotateHelix(center, h.begin,h.end, delta);
-
- // Re-assigns unpaired atoms
- boolean over = false;
- helixStart = _r.getCoord(h.begin);
- helixStop = _r.getCoord(h.end);
- pHelR = computeAngle(center,helixStop)-base;
- pHelL = computeAngle(center,helixStart)-base;
-
- i = h.begin-1;
- Vector nextBases = new Vector();
- while(!over)
- {
- if(i<0)
- {over = true;}
- else
- {
- if (_r.getBP(i)==-1)
- {nextBases.add(new Integer(i));}
- else
- {over = true;}
- }
- i--;
- }
- Vector prevBases = new Vector();
- over = false;
- i=h.end+1;
- while(!over)
- {
- if(i>=_r.getSize())
- {over = true;}
- else
- {
- if (_r.getBP(i)==-1)
- {prevBases.add(new Integer(i));}
- else
- {over = true;}
- }
- i++;
- }
- double radius = center.distance(helixStart);
- double anglePrev = normalizeAngle(pLimL-pHelR);
-
- for(i=0;i=(2.0*Math.PI)-base)
- { angle -= 2.0*Math.PI; }
- return angle;
- }
-
-
-
- private double computeAngle(RealPoint center, RealPoint p)
- {
- double dist = center.distance(p);
- double angle = Math.asin((p.y-center.y)/dist);
- if (p.x-center.x<0)
- { angle = Math.PI-angle; }
- return angle;
- }
-
-
- private RealPoint rotatePoint(RealPoint center,RealPoint p, double angle)
- {
- double dist = p.distance(center);
- double oldAngle = Math.asin((p.y-center.y)/dist);
- if (p.x-center.x<0)
- { oldAngle = Math.PI-oldAngle; }
- double newX = (center.x+dist*Math.cos(oldAngle+angle));
- double newY = (center.y+dist*Math.sin(oldAngle+angle));
- return new RealPoint(newX,newY);
- }
-
- private void rotateHelix(RealPoint center, int i, int j, double angle)
- {
-
- for(int k=i;k<=j;k++)
- {
- RealPoint oldp = _r.getCoord(k);
- RealPoint newp = rotatePoint(center,oldp,angle);
- _r.setCoord(k,newp );
- if ((k!=i)&&(k!=j))
- {
- RealPoint oldc = _r._em._centers[k];
- RealPoint newc = rotatePoint(center,oldc,angle);
- _r._em._centers[k]=newc;
- }
- }
- repaint();
- }
- /**
- * Returns the RNA secondary structure diplayed by this panel as a well-parenthesized
- * word, accordingly to the DBN format
- * @return This panel's secondary structure
- */
- public String getStructDBN()
- {
- String result = "";
- for(int i=0;i<_r.getSize();i++)
- {
- int j = _r.getBP(i);
- if (j==-1)
- {
- result += ".";
- }
- else if (i>j)
- {
- result += ")";
- }
- else
- {
- result += "(";
- }
- }
-
- return result;
- }
-
- /**
- * Returns the raw nucleotides sequence for the displayed RNA
- * @return The RNA sequence
- */
- public String getSeq()
- {
- String result = "";
- for(int i=0;i<_r.getSize();i++)
- {
- result += _r.getRes(i);
- }
- return result;
- }
-
- /**
- * Returns the color used to draw backbone bounds.
- * @return The color used to draw backbone bounds
- */
- public Color getBackboneColor() {
- return BACKBONE_COLOR;
- }
-
- /**
- * Sets the color to be used for drawing backbone interactions.
- * @param backbone_color The new color for the backbone bounds
- */
- public void setBackboneColor(Color backbone_color) {
- BACKBONE_COLOR = backbone_color;
- }
-
- /**
- * Returns the color to be used for displaying the inner part of bases.
- * @return The color for the inner part of bases
- */
- public Color getBaseInnerColor() {
- return BASE_INNER_COLOR;
- }
-
- /**
- * Sets the color to be used for displaying the inner part of bases.
- * @param base_inner_color The new color for the inner part of bases
- */
- public void setBaseInnerColor(Color base_inner_color) {
- BASE_INNER_COLOR = base_inner_color;
- }
-
-
- /**
- * Returns the color to be used for drawing nucleotide names.
- * @return The color for nucleotide names
- */
- public Color getBaseNameColor() {
- return BASE_NAME_COLOR;
- }
-
-
- /**
- * Sets the color to be used for drawing nucleotide names.
- * @param base_name_color The new color for nucleotide names
- */
- public void setBaseNameColor(Color base_name_color) {
- BASE_NAME_COLOR = base_name_color;
- }
-
-
- /**
- * Returns the color to be used for displaying nucleotides numbers.
- * @return The color of nucleotide numbers
- */
- public Color getBaseNumbersColor() {
- return BASE_NUMBERS_COLOR;
- }
-
- /**
- * Sets the color to be used for displaying nucleotides numbers.
- * @param base_numbers_color The new color of nucleotide numbers
- */
- public void setBaseNumbersColor(Color base_numbers_color) {
- BASE_NUMBERS_COLOR = base_numbers_color;
- }
-
- /**
- * Returns the color used to display the external part of nucleotides (external circle).
- * @return The color used to display the external part of nucleotides
- */
- public Color getBaseOutlineColor() {
- return BASE_OUTLINE_COLOR;
- }
-
- /**
- * Sets the new color used to display the external part of nucleotides (external circle).
- * @param base_outline_color The new color of the external nucleotides circle
- */
- public void setBaseOutlineColor(Color base_outline_color) {
- BASE_OUTLINE_COLOR = base_outline_color;
- }
-
-
- /**
- * Returns the color used to display hydrogen bonds (base pairings)
- * @return The color of hydrogen bonds
- */
- public Color getBondColor() {
- return BOND_COLOR;
- }
-
- /**
- * Returns the title of this panel
- * @return The title
- */
- public String getTitle() {
- return _title;
- }
-
- /**
- * Sets the new color to be used for hydrogen bonds (base pairings)
- * @param bond_color The new color for hydrogen bonds
- */
- public void setBondColor(Color bond_color) {
- BOND_COLOR = bond_color;
- }
-
- /**
- * Sets the size of the border, i.e. the empty space between the end of the drawing area
- * and the actual border.
- * @param b The new border size
- */
- public void setBorderSize(int b) {
- BORDER = b;
- }
-
- /**
- * Returns the size of the border, i.e. the empty space between the end of the drawing area
- * @return The border size
- */
- public int getBorderSize() {
- return BORDER;
- }
-
- /**
- * Recomputes the layout of the secondary structure, using a previously set
- * drawing strategy.
- * @see #DRAW_MODE_CIRCLE
- * @see #DRAW_MODE_RADIATE
- */
- public void redoLayout()
- {
- setRNA(new String(_r._str._seq),_r._str.getStructDBN());
- }
-
- /**
- * Recomputes the layout of the secondary structure. The result will
- * depend on the chosen drawing strategy.
- * @param drawMode The drawing strategy
- * @see #DRAW_MODE_CIRCLE
- * @see #DRAW_MODE_RADIATE
- */
- public void redoLayout(int drawMode)
- {
- _drawMode = drawMode;
- setRNA(new String(_r._str._seq),_r._str.getStructDBN());
- }
-
- private void buildPopupMenu()
- {
- // Reset menuitem
- JMenuItem redisplay = new JMenuItem("Reset");
- redisplay.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- reset();
- }});
-
- // Drawing algorithm menu
- JMenu submenuAlgo = new JMenu("Redraw");
- JMenuItem algoCircle = new JMenuItem("Circular");
- algoCircle.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- setRNA(_r._str, VARNAPanel.DRAW_MODE_CIRCLE);
- }});
- JMenuItem algoRadiate = new JMenuItem("Radiate");
- algoRadiate.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- setRNA(_r._str,VARNAPanel.DRAW_MODE_RADIATE);
- }});
- submenuAlgo.add(algoCircle);
- submenuAlgo.add(algoRadiate);
-
- // Export menu
- JMenu submenuExport = new JMenu("Export");
- JMenu submenuExportStructure = new JMenu("Structure");
- JMenu submenuExportImage = new JMenu("Image");
- JMenuItem exportDBN = new JMenuItem("DBN (dotbracket) Format");
- exportDBN.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UIExportDBN();
- }});
- JMenuItem exportBPSEQ = new JMenuItem("BPSEQ Format");
- exportDBN.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UIExportBPSEQ();
- }});
- JMenuItem exportCT = new JMenuItem("CT Format");
- exportDBN.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UIExportCT();
- }});
- JMenuItem exportEPS = new JMenuItem("EPS Picture");
- exportEPS.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UIExportEPS();
- }});
- JMenuItem exportXFIG = new JMenuItem("XFIG File");
- exportXFIG.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UIExportXFIG();
- }});
- JMenuItem exportJPEG = new JMenuItem("JPEG Picture");
- exportJPEG.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UIExportJPEG();
- }});
-
- submenuExport.add(submenuExportImage);
- submenuExport.add(submenuExportStructure);
- submenuExportStructure.add(exportDBN);
- submenuExportStructure.add(exportCT);
- submenuExportStructure.add(exportBPSEQ);
- submenuExportImage.add(exportEPS);
- submenuExportImage.add(exportXFIG);
- submenuExportImage.add(exportJPEG);
-
- // Input menu
- JMenu submenuImport = new JMenu("Open");
- JMenuItem manualInput = new JMenuItem("User input");
- manualInput.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UIManualInput();
- }});
- JMenuItem diskInput = new JMenuItem("File");
- diskInput.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UIFileInput();
- }});
-
- submenuImport.add(diskInput);
- submenuImport.add(manualInput);
-
- // Input menu
- JMenu submenuDisplay = new JMenu("Display");
- JMenu colorsDisplay = new JMenu("Colors");
- JMenuItem backgroundDisplay = new JMenuItem("Background");
- backgroundDisplay.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UIBackgroundDisplay();
- }});
- JMenuItem baseInnerDisplay = new JMenuItem("Bases inner");
- baseInnerDisplay.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UIBaseInnerDisplay();
- }});
- JMenuItem baseOuterDisplay = new JMenuItem("Bases outer");
- baseOuterDisplay.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UIBaseOuterDisplay();
- }});
- JMenuItem backboneDisplay = new JMenuItem("Backbone");
- backboneDisplay.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UIBackboneColorDisplay();
- }});
- JMenuItem bondsDisplay = new JMenuItem("Bonds");
- bondsDisplay.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UIBondsDisplay();
- }});
- JMenu fontsDisplay = new JMenu("Fonts");
- JMenuItem titleDisplay = new JMenuItem("Title");
- titleDisplay.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UITitleDisplay();
- }});
- JMenuItem baseDisplay = new JMenuItem("Bases");
- baseDisplay.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UIBaseDisplay();
- }});
- JMenuItem titleContentDisplay = new JMenuItem("Title");
- titleContentDisplay.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UITitleContentDisplay();
- }});
- JMenuItem borderDisplay = new JMenuItem("Border Size");
- borderDisplay.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UIBorderDisplay();
- }});
- JMenuItem numPeriodDisplay = new JMenuItem("Num Period");
- numPeriodDisplay.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent arg0) {
- UINumPeriod();
- }});
- colorsDisplay.add(backgroundDisplay);
- colorsDisplay.add(backboneDisplay);
- colorsDisplay.add(baseInnerDisplay);
- colorsDisplay.add(baseOuterDisplay);
- colorsDisplay.add(bondsDisplay);
- fontsDisplay.add(titleDisplay);
- fontsDisplay.add(baseDisplay);
- submenuDisplay.add(colorsDisplay);
- submenuDisplay.add(fontsDisplay);
- submenuDisplay.add(titleContentDisplay);
- submenuDisplay.add(borderDisplay);
- submenuDisplay.add(numPeriodDisplay);
-
- popup.add(submenuImport);
- popup.add(submenuExport);
- popup.addSeparator();
- popup.add(submenuAlgo);
- popup.addSeparator();
- popup.add(submenuDisplay);
- //popup.add(redisplay);
- this.add(popup);
- }
-
- private void UIBaseDisplay()
- {
- String family = selectFont("Base font", "Please select a new font for bases:",this.getFont());
- setBaseFontFamily(family);
- }
-
- private void UITitleDisplay()
- {
- String family = selectFont("Title font", "Please select a new font for the title:", this.getFont());
- setTitleFontFamily(family);
- }
-
- private String selectFont(String title, String message,Font defaultFont)
- {
- GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
- String [] polices = ge.getAvailableFontFamilyNames();
- JLabel msg = new JLabel(message);
- JComboBox l = new JComboBox(polices);
- JPanel p = new JPanel();
- p.setLayout(new GridLayout(1,2));
- p.add(l);
- p.add(msg);
- JOptionPane.showConfirmDialog(this,l,title,JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
- return (String)l.getSelectedItem();
- }
-
- private void UIBaseOuterDisplay()
- {
- Color c = JColorChooser.showDialog(this, "Choose new base outline color", this.getBackground());
- if (c != null)
- { this.setBaseOutlineColor(c); }
- }
-
- private void UIBaseInnerDisplay()
- {
- Color c = JColorChooser.showDialog(this, "Choose new base filling color", this.getBackground());
- if (c != null)
- { this.setBaseInnerColor(c); }
- }
-
- private void UIBackboneColorDisplay()
- {
- Color c = JColorChooser.showDialog(this, "Choose new backbone color", this.getBackground());
- if (c != null)
- { this.setBackboneColor(c); }
- }
- private void UIBondsDisplay()
- {
- Color c = JColorChooser.showDialog(this, "Choose new bonds color", this.getBackground());
- if (c != null)
- { this.setBondColor(c); }
- }
-
- private void UIBackgroundDisplay()
- {
- Color c = JColorChooser.showDialog(this, "Choose new background color", this.getBackground());
- if (c != null)
- { this.setBackground(c); }
- }
-
- private void UIExportDBN()
- {
- JFileChooser fc = new JFileChooser();
- if (fc.showSaveDialog(VARNAPanel.this)==JFileChooser.APPROVE_OPTION)
- {
- _r._str.exportDBN(fc.getSelectedFile().getAbsolutePath(), this._title);
- }
- }
-
- private void UIExportBPSEQ()
- {
- JFileChooser fc = new JFileChooser();
- if (fc.showSaveDialog(VARNAPanel.this)==JFileChooser.APPROVE_OPTION)
- {
- _r._str.exportBPSEQ(fc.getSelectedFile().getAbsolutePath(), this._title);
- }
- }
-
- private void UIExportCT()
- {
- JFileChooser fc = new JFileChooser();
- if (fc.showSaveDialog(VARNAPanel.this)==JFileChooser.APPROVE_OPTION)
- {
- _r._str.exportCT(fc.getSelectedFile().getAbsolutePath(), this._title);
- }
- }
-
-
- private void UIExportEPS()
- {
- JFileChooser fc = new JFileChooser();
- if (fc.showSaveDialog(VARNAPanel.this)==JFileChooser.APPROVE_OPTION)
- {
- _r.saveEmbeddedRNAEPS(fc.getSelectedFile().getAbsolutePath(), _title,_numPeriod);
- }
- }
-
- private void UIExportXFIG()
- {
- JFileChooser fc = new JFileChooser();
- if (fc.showSaveDialog(VARNAPanel.this)==JFileChooser.APPROVE_OPTION)
- {
- _r.saveEmbeddedRNAXFIG(fc.getSelectedFile().getAbsolutePath(), _title,_numPeriod);
- }
- }
-
-
- private void UIExportJPEG()
- {
- JFileChooser fc = new JFileChooser();
- if (fc.showSaveDialog(VARNAPanel.this)==JFileChooser.APPROVE_OPTION)
- {
- saveToJPEG(fc.getSelectedFile().getAbsolutePath());
- }
- }
-
- private void UIFileInput()
- {
- JFileChooser fc = new JFileChooser();
- if (fc.showOpenDialog(VARNAPanel.this)==JFileChooser.APPROVE_OPTION)
- {
- RNASecStr s = RNASecStr.loadSecStr(fc.getSelectedFile().getAbsolutePath());
- setRNA(s);
- }
-
- }
-
- private void UIManualInput()
- {
- JPanel p = new JPanel();
- JPanel pup = new JPanel();
- JPanel pdown = new JPanel();
- p.setLayout(new GridLayout(2,1));
- pup.setLayout(new FlowLayout(FlowLayout.LEFT));
- pdown.setLayout(new FlowLayout(FlowLayout.LEFT));
-
- Font _textFieldsFont = Font.decode("MonoSpaced-PLAIN-12");
-
- JLabel lseq = new JLabel("Sequence: ");
- JTextField tseq = new JTextField(getSeq());
- JLabel lstr = new JLabel("Structure: ");
- JTextField tstr = new JTextField(this.getStructDBN());
- tstr.setPreferredSize(new Dimension(400,tstr.getPreferredSize().height));
- tseq.setPreferredSize(new Dimension(400,tseq.getPreferredSize().height));
- tstr.setFont(_textFieldsFont);
- tseq.setFont(_textFieldsFont);
- pup.add(lseq);
- pup.add(tseq);
- pdown.add(lstr);
- pdown.add(tstr);
- p.add(pup);
- p.add(pdown);
- if (JOptionPane.showConfirmDialog(this,p,"Input sequence/structure",JOptionPane.OK_CANCEL_OPTION)==JOptionPane.OK_OPTION)
- {
- setRNA(tseq.getText(),tstr.getText());
- }
- }
-
- private void UINumPeriod()
- {
- JSlider numPeriodSlider = new JSlider(JSlider.HORIZONTAL,1 , (_r.getSize())/2, _numPeriod);
- //Turn on labels at major tick marks.
- numPeriodSlider.setMajorTickSpacing(10);
- numPeriodSlider.setMinorTickSpacing(5);
- numPeriodSlider.setPaintTicks(true);
- numPeriodSlider.setPaintLabels(true);
- if (JOptionPane.showConfirmDialog(this,numPeriodSlider,"Set new numbering period",JOptionPane.OK_CANCEL_OPTION)==JOptionPane.OK_OPTION)
- {
- this.setNumPeriod(numPeriodSlider.getValue());
- }
- }
-
- private void UIBorderDisplay()
- {
- JSlider borderSlider = new JSlider(JSlider.HORIZONTAL,10 , 10+(getWidth()-10)/2, BORDER);
- //Turn on labels at major tick marks.
- borderSlider.setMajorTickSpacing(50);
- borderSlider.setMinorTickSpacing(10);
- borderSlider.setPaintTicks(true);
- borderSlider.setPaintLabels(true);
- if (JOptionPane.showConfirmDialog(this,borderSlider,"Set new border size",JOptionPane.OK_CANCEL_OPTION)==JOptionPane.OK_OPTION)
- {
- this.setBorderSize(borderSlider.getValue());
- }
- }
-
-
- private void UITitleContentDisplay() {
- String res = JOptionPane.showInputDialog(this, "Input title", this.getTitle());
- if (res != null)
- {
- this.setTitle(res);
- }
- }
-
- public void saveToJPEG(String filename) {
- Dimension size = getSize();
- BufferedImage myImage =
- new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
- Graphics2D g2 = myImage.createGraphics();
- this.paint(g2);
- try {
- OutputStream out = new FileOutputStream(filename);
- JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
- encoder.encode(myImage);
- out.close();
- } catch (Exception e) {
- System.out.println(e);
- }
- }
-
-
-}
+/*
+ * VARNAPanel.java
+ *
+ * Created on 24. březen 2008, 11:21
+ */
+package varna;
+
+import java.awt.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.geom.*;
+import java.awt.image.BufferedImage;
+import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.text.ParseException;
+import java.util.Vector;
+
+import javax.swing.*;
+
+import com.sun.image.codec.jpeg.JPEGCodec;
+import com.sun.image.codec.jpeg.JPEGImageEncoder;
+import java.io.FileWriter;
+import varna.export.PSExport;
+import varna.export.SVGExport;
+
+/**
+ *
+ * @author lopik
+ */
+public class VARNAPanel extends javax.swing.JPanel {
+ private boolean _initialAutoFit = true;
+
+ public void setNumOffset(int _numOffset) {
+ this._numOffset = _numOffset;
+ System.out.println("offset:" + _numOffset);
+ }
+
+ public int getNumOffset() {
+ return _numOffset;
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // //GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jPopupMenuSaveHelix = new javax.swing.JPopupMenu();
+ jMenuItemSaveHelix = new javax.swing.JMenuItem();
+
+ jMenuItemSaveHelix.setText("Save helix");
+ jMenuItemSaveHelix.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jMenuItemSaveHelixActionPerformed(evt);
+ }
+ });
+ jPopupMenuSaveHelix.add(jMenuItemSaveHelix);
+
+ addMouseWheelListener(new java.awt.event.MouseWheelListener() {
+ public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
+ formMouseWheelMoved(evt);
+ }
+ });
+ addMouseListener(new java.awt.event.MouseAdapter() {
+ public void mousePressed(java.awt.event.MouseEvent evt) {
+ formMousePressed(evt);
+ }
+ public void mouseReleased(java.awt.event.MouseEvent evt) {
+ formMouseReleased(evt);
+ }
+ });
+ addComponentListener(new java.awt.event.ComponentAdapter() {
+ public void componentResized(java.awt.event.ComponentEvent evt) {
+ formComponentResized(evt);
+ }
+ });
+ addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
+ public void mouseDragged(java.awt.event.MouseEvent evt) {
+ formMouseDragged(evt);
+ }
+ public void mouseMoved(java.awt.event.MouseEvent evt) {
+ formMouseMoved(evt);
+ }
+ });
+ setLayout(new java.awt.BorderLayout());
+ }// //GEN-END:initComponents
+
+private void formMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMousePressed
+ _dragButton = evt.getButton();
+ _dragged = false;
+ if (evt.getButton() == 1) {
+ if (_realCoords != null) {
+ double dist = Double.MAX_VALUE;
+ for (int i = 0; i < _realCoords.length; i++) {
+ double d2 = Math.sqrt(Math.pow((_realCoords[i].x - evt.getX()), 2) + Math.pow((_realCoords[i].y - evt.getY()), 2));
+ if ((dist > d2) && (_r._str.getBP(i) != -1)) {
+ _selectedBase = i;
+ dist = d2;
+ }
+ }
+ //System.out.println("[1]"+_selectedBase);
+ }
+ } else if (evt.getButton() == 3) {
+ _panOffsetDragBegin = new RealPoint(evt.getX(), evt.getY());
+ } else {
+ }
+}//GEN-LAST:event_formMousePressed
+
+private void formMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseDragged
+ _dragged = true;
+ if (_dragButton == 1) {
+ if (_selectedBase != -1) {
+ if (_drawMode == VARNAPanel.DRAW_MODE_CIRCLE) {
+ moveSingleAtom(_selectedBase, evt.getX(), evt.getY());
+ } else {
+ moveHelixAtom(_selectedBase, evt.getX(), evt.getY());
+ }
+ }
+ }
+ if (_dragButton == 3) {
+ _panOffsetDragging = new RealPoint(evt.getX() - _panOffsetDragBegin.x, evt.getY() - _panOffsetDragBegin.y);
+ repaint();
+ }
+}//GEN-LAST:event_formMouseDragged
+
+private void formMouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_formMouseWheelMoved
+ double scale = 1.1 * evt.getWheelRotation();
+ if (scale > 0) {
+ _scaleFactor *= scale;
+ } else {
+ _scaleFactor /= -scale;
+ }
+ repaint();
+
+}//GEN-LAST:event_formMouseWheelMoved
+
+private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
+ recalculateInitialOffset();
+}//GEN-LAST:event_formComponentResized
+
+private void formMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseReleased
+ if (evt.getButton() == 1) {
+ recalculateInitialOffset();
+ } else if (evt.getButton() == 3) {
+// _selectedBase = -1;
+ if (!_dragged) {
+ if (!_hooverHelix.equals(new Range())) {
+ jPopupMenuSaveHelix.show(this, evt.getX(), evt.getY());
+ } else {
+ popup.show(this, evt.getX(), evt.getY());
+ }
+
+ } else {
+ _panOffset.add(_panOffsetDragging);
+ _panOffsetDragging = new RealPoint();
+ }
+ }
+}//GEN-LAST:event_formMouseReleased
+
+private void formMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseMoved
+ if (_realCoords != null) {
+ double dist = Double.MAX_VALUE;
+ for (int i = 0; i < _realCoords.length; i++) {
+ double d2 = Math.sqrt(Math.pow((_realCoords[i].x - evt.getX()), 2) + Math.pow((_realCoords[i].y - evt.getY()), 2));
+ if ((dist > d2) && (_r._str.getBP(i) != -1)) {
+ _selectedBase = i;
+ dist = d2;
+ }
+ }
+ Range newHooverHelix;
+ if (dist / _scaleFactor < 30) {
+ newHooverHelix = _r.getHelix(_selectedBase);
+ } else {
+ newHooverHelix = new Range();
+ }
+ if (!_hooverHelix.equals(newHooverHelix)) {
+ repaint();
+ }
+ _hooverHelix = newHooverHelix;
+ //System.out.println("dist:"+dist/_scaleFactor);
+ }
+
+}//GEN-LAST:event_formMouseMoved
+
+private void jMenuItemSaveHelixActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSaveHelixActionPerformed
+ JFileChooser jFileChooserSave = new javax.swing.JFileChooser();
+
+ jFileChooserSave.setCurrentDirectory(new java.io.File("/home/lopik/prog/python"));
+ jFileChooserSave.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
+ jFileChooserSave.setSelectedFile(new java.io.File("/home/lopik/prog/python/hairpin.fa"));
+
+ if (jFileChooserSave.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
+ if (jFileChooserSave.getSelectedFile().exists()) {
+ if (JOptionPane.YES_OPTION != JOptionPane.showConfirmDialog(this, "File " + jFileChooserSave.getSelectedFile().getName() + " exists.\nOverwrite?")) {
+ return;
+ }
+ }
+ _r.getRNASecStr().exportDBN(jFileChooserSave.getSelectedFile().getAbsolutePath(), "[sub]" + _r, _hooverHelix);
+ }
+}//GEN-LAST:event_jMenuItemSaveHelixActionPerformed
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JMenuItem jMenuItemSaveHelix;
+ private javax.swing.JPopupMenu jPopupMenuSaveHelix;
+ // End of variables declaration//GEN-END:variables
+ private static final long serialVersionUID = 1L;
+ static final int DRAW_MODE_UNKNOWN = -1;
+ /**
+ * Selects the "Feynman diagram" drawing algorithm that places
+ * the bases on a circle and draws the base-pairings as chords
+ * of the circle graph.
+ */
+ public static final int DRAW_MODE_CIRCLE = 1;
+ /**
+ * Selects the "tree drawing" algorithm. Draws
+ * each loop on a circle whose radius depends on the number of bases involved
+ * in the loop. As some helices can be overlapping in the result, basic
+ * interaction is provided so that the user can "disentangle" the drawing
+ * by spinning the helices around the axis defined by their multiloop
+ * (bulge or internal loop) origin. This is roughly the initial placement
+ * strategy of RNAViz.
+ * @see RNAViz
+ */
+ public static final int DRAW_MODE_RADIATE = 2;
+ private int BORDER = 15;
+ private EmbeddedRNA _r = new EmbeddedRNA();
+ private Color BACKBONE_COLOR = Color.black;
+ private Color BOND_COLOR = Color.blue;
+ private Color BASE_OUTLINE_COLOR = Color.DARK_GRAY;
+ private Color BASE_INNER_COLOR = new Color(230, 230, 230);
+ private Color BASE_NUMBERS_COLOR = Color.DARK_GRAY;
+ private Color BASE_NAME_COLOR = Color.black;
+ private Color TITLE_COLOR = Color.black;
+ private int TITLE_HEIGHT = 30;
+ private int _numPeriod = 5;
+ private boolean _autoFit = true;
+ private boolean _autoCenter = true;
+ private Font _titleFont;
+ private String _title = "";
+ private String _titleFontFamily = "Arial";
+ private String _titleFontStyle = "PLAIN";
+ private int _titleFontSize = 18;
+ private String _baseFontFamily = "Arial";
+ private String _baseFontStyle = "BOLD";
+ private int _baseFontSize = 18;
+ private Font _baseNameFont;
+ private int _drawMode = DRAW_MODE_UNKNOWN;
+ private BasicStroke dashed;
+ private RealPoint[] _realCoords = new RealPoint[0];
+ private int _numOffset = 1;
+
+
+ private int _selectedBase = -1;
+ private double _scaleFactor = 1.0;
+ private RealPoint _offsetPanel = new RealPoint();
+ private RealPoint _offsetRNA = new RealPoint();
+ private RealRectangle _rnaInitialBoundigBox;
+ private RealPoint _initialOffset = new RealPoint();
+ private RealPoint _panOffset = new RealPoint();
+ private RealPoint _panOffsetDragging = new RealPoint();
+ private RealPoint _panOffsetDragBegin = new RealPoint();
+ private int _dragButton = 0;
+ private boolean _dragged = false;
+ private Range _hooverHelix = new Range();
+ private boolean[] _structureSelection;
+ private Color SELECTED_HELIX_COLOR = Color.red;
+ private Color BASE_OUTLINE_COLOR_SELECTED = Color.DARK_GRAY;
+ private Color BASE_INNER_COLOR_SELECTED = Color.BLACK;
+ private Color BASE_NAME_COLOR_SELECTED = Color.WHITE;
+
+ /**
+ * Creates an RNA 2D panel with initially displays the empty structure.
+ */
+ public VARNAPanel() {
+ this("", "", DRAW_MODE_RADIATE);
+ }
+
+ /**
+ * Creates an RNA 2D panel, and creates and displays an RNA coupled
+ * with its secondary structure formatted as a well-balanced parenthesis
+ * with dots word (DBN format).
+ * @param seq The raw nucleotide sequence
+ * @param str The secondary structure in DBN format
+ */
+ public VARNAPanel(String seq, String str) {
+ this(seq, str, DRAW_MODE_RADIATE);
+ }
+
+ /**
+ * Creates an RNA 2D panel, and creates and displays an RNA coupled
+ * with its secondary structure formatted as a well-balanced parenthesis
+ * with dots word (DBN format). Allows the user to choose the drawing
+ * algorithm to be used.
+ * @param seq The raw nucleotide sequence
+ * @param str The secondary structure in DBN format
+ * @param drawMode The drawing mode
+ * @see #DRAW_MODE_CIRCLE
+ * @see #DRAW_MODE_RADIATE
+ */
+ public VARNAPanel(String seq, String str, int drawMode) {
+ this(seq, str, drawMode, "");
+ }
+
+ /**
+ * Creates an RNA 2D panel, and creates and displays an RNA coupled
+ * with its secondary structure formatted as a well-balanced parenthesis
+ * with dots word (DBN format). Allows the user to choose the drawing
+ * algorithm to be used. Additionally, sets the panel's title.
+ * @param seq The raw nucleotide sequence
+ * @param str The secondary structure in DBN format
+ * @param drawMode The drawing mode
+ * @param title The panel title
+ * @see #DRAW_MODE_CIRCLE
+ * @see #DRAW_MODE_RADIATE
+ */
+ public VARNAPanel(String seq, String str, int drawMode, String title) {
+ super();
+ _title = title;
+ _drawMode = drawMode;
+ setRNA(seq, str);
+ init();
+ initComponents();
+ }
+ JPopupMenu popup = new JPopupMenu();
+
+ private void init() {
+ float[] ds = new float[2];
+ ds[0] = 5.0f;
+ ds[1] = 5.0f;
+ dashed = new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 3.0f, ds, 0.0f);
+ this.setBackground(Color.white);
+ GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
+ Font[] avlFonts = ge.getAllFonts();
+
+ _baseNameFont = Font.decode("" + _baseFontFamily + "-" + _baseFontStyle + "-" + _baseFontSize);
+ _titleFont = Font.decode("" + _titleFontFamily + "-" + _titleFontStyle + "-" + _titleFontSize);
+ this.setFont(_baseNameFont);
+
+ buildPopupMenu();
+
+ }
+
+ void reset() {
+ setRNA(_r._str, _drawMode);
+ }
+
+ /**
+ * Sets the RNA secondary structure to be drawn in this panel, using the default layout algorithm.
+ * In addition to the raw nucleotides sequence, the secondary structure is given
+ * in the so-called "Dot-bracket notation" (DBN) format.
+ * This format is a well-parenthesized word over the alphabet '(',')','.'.
+ * Ex: ((((((((....))))..(((((...))).))))))
+ * Returns true
if the sequence/structure couple could be parsed into a
+ * valid secondary structure, and false
otherwise.
+ * @param seq The raw nucleotides sequence
+ * @param str The secondary structure
+ * @return true
if the sequence/structure couple could be parsed into a
+ * valid secondary structure, false
otherwise
+ */
+ public boolean setRNA(String seq, String str) {
+ return setRNA(seq, str, _drawMode);
+ }
+
+ /**
+ * Sets the RNA secondary structure to be drawn in this panel, using a given layout algorithm.
+ * @param r The new secondary structure
+ * @param drawMode The drawing algorithm
+ */
+ public void setRNA(RNASecStr r, int drawMode) {
+ _drawMode = drawMode;
+ setRNA(r);
+ }
+
+ /**
+ * Sets the RNA secondary structure to be drawn in this panel, using the current drawing algorithm.
+ * @param r The new secondary structure
+ */
+ public void setRNA(RNASecStr r) {
+ if (r != null) {
+ Embedding coords;
+ switch (_drawMode) {
+ case DRAW_MODE_RADIATE:
+ coords = EmbeddedRNA.drawRNASecStr(r);
+ break;
+ case DRAW_MODE_CIRCLE:
+ coords = EmbeddedRNA.drawRNASecStrCircle(r);
+ break;
+ default:
+ coords = new Embedding();
+ break;
+ }
+ _r = new EmbeddedRNA(r, coords);
+ }
+ recalculateInitialOffset();
+ _structureSelection = new boolean[_r.getSize()];
+ }
+
+ /**
+ * Sets the RNA secondary structure to be drawn in this panel, using a given layout algorithm.
+ * In addition to the raw nucleotides sequence, the secondary structure is given
+ * in the so-called "Dot-bracket notation" (DBN) format.
+ * This format is a well-parenthesized word over the alphabet '(',')','.'.
+ * Ex: ((((((((....))))..(((((...))).))))))
+ * Returns true
if the sequence/structure couple could be parsed into a
+ * valid secondary structure, and false
otherwise.
+ * @param seq The raw nucleotides sequence
+ * @param str The secondary structure
+ * @param drawMode The drawing algorithm
+ * @return true
if the sequence/structure couple could be parsed into a
+ * valid secondary structure, false
otherwise
+ */
+ public boolean setRNA(String seq, String str, int drawMode) {
+ _drawMode = drawMode;
+ if (seq.length() != str.length()) {
+ System.err.println("Sequence length " + seq.length() + " differs from that of secondary structure " + str.length() + ". \nAdapting sequence length ...");
+ if (seq.length() < str.length()) {
+ while (seq.length() < str.length()) {
+ seq += " ";
+ }
+ } else {
+ seq = seq.substring(0, str.length());
+ }
+ }
+ RNASecStr r = null;
+ try {
+ r = new RNASecStr(seq, str);
+ } catch (ParseException e) {
+ System.err.println(e.getMessage());
+ System.err.println("Invalid secondary structure at char " + e.getErrorOffset() + ".");
+ return false;
+ }
+ setRNA(r);
+ return true;
+// Embedding coords;
+// switch (_drawMode) {
+// case DRAW_MODE_RADIATE:
+// coords = EmbeddedRNA.drawRNASecStr(r);
+// break;
+// case DRAW_MODE_CIRCLE:
+// coords = EmbeddedRNA.drawRNASecStrCircle(r);
+// break;
+// default:
+// coords = new Embedding();
+// break;
+// }
+// _r = new EmbeddedRNA(r, coords);
+// recalculateInitialOffset();
+// return true;
+ }
+
+ public void setStructureSelection(String str) {
+ for (int i = 0; i < str.length(); i++) {
+ if (i > _structureSelection.length - 1) {
+ return;
+ }
+ _structureSelection[i] = str.charAt(i) != '-';
+ }
+ }
+
+ private void recalculateInitialOffset() {
+ _rnaInitialBoundigBox = _r.getBBox();
+ double offX = (getX() + (getWidth() - Math.round(_rnaInitialBoundigBox.width * _scaleFactor)) / 2.0);
+ double offY = (getY() + (getHeight() - Math.round(_rnaInitialBoundigBox.height * _scaleFactor)) / 2.0);
+ _initialOffset = new RealPoint(offX, offY);
+ repaint();
+ }
+
+ /**
+ * Sets the new style of the title font.
+ * @param newStyle A string that describes the new font style ("PLAIN","BOLD", "BOLDITALIC", or "ITALIC")
+ */
+ public void setTitleFontStyle(String newStyle) {
+ _titleFontStyle = newStyle;
+ _titleFont = Font.decode("" + _titleFontFamily + "-" + _titleFontStyle + "-" + _titleFontSize);
+ }
+
+ /**
+ * Sets the new size of the title font.
+ * @param newSize The new size of the title font
+ */
+ public void setTitleFontSize(int newSize) {
+ _titleFontSize = newSize;
+ _titleFont = Font.decode("" + _titleFontFamily + "-" + _titleFontStyle + "-" + _titleFontSize);
+ }
+
+ /**
+ * Sets the new font family to be used for the title. Available fonts are system-specific, yet
+ * it seems that "Arial", "Dialog", and "MonoSpaced" are almost always available.
+ * @param newFamily New font family used for the title
+ */
+ public void setTitleFontFamily(String newFamily) {
+ _titleFontFamily = newFamily;
+ _titleFont = Font.decode("" + _titleFontFamily + "-" + _titleFontStyle + "-" + _titleFontSize);
+ }
+
+ /**
+ * Sets the color to be used for the title.
+ * @param newColor A color used to draw the title
+ */
+ public void setTitleFontColor(Color newColor) {
+ TITLE_COLOR = newColor;
+ }
+
+ /**
+ * Sets the new style of the base name.
+ * @param newStyle A string that describes the new font style ("PLAIN","BOLD", "BOLDITALIC", or "ITALIC")
+ */
+ public void setBaseFontStyle(String newStyle) {
+ _baseFontStyle = newStyle;
+ _baseNameFont = Font.decode("" + _titleFontFamily + "-" + _titleFontStyle + "-" + _titleFontSize);
+ }
+
+ /**
+ * Sets the new size of the base name.
+ * @param newSize The new size of the base font
+ */
+ public void setBaseFontSize(int newSize) {
+ _baseFontSize = newSize;
+ _baseNameFont = Font.decode("" + _titleFontFamily + "-" + _titleFontStyle + "-" + _titleFontSize);
+ }
+
+ /**
+ * Sets the new font family to be used for the base names. Available fonts are system-specific, yet
+ * it seems that "Arial", "Dialog", and "MonoSpaced" are almost always available.
+ * @param newFamily New font family used for the base names
+ */
+ public void setBaseFontFamily(String newFamily) {
+ _baseFontFamily = newFamily;
+ _baseNameFont = Font.decode("" + _titleFontFamily + "-" + _titleFontStyle + "-" + _titleFontSize);
+ }
+
+ /**
+ * Sets the color to be used for the base names.
+ * @param newColor A color used to draw the base names
+ */
+ public void setBaseFontColor(Color newColor) {
+ BASE_NAME_COLOR = newColor;
+ }
+
+ /**
+ * Sets the panel's title, giving a short description of the RNA secondary structure.
+ * @param title The new title
+ */
+ public void setTitle(String title) {
+ _title = title;
+ }
+
+ /**
+ * Sets the background color of the Panel.
+ * @param newColor A color used for the backgound
+ */
+ public void setBackground(Color newColor) {
+ super.setBackground(newColor);
+ }
+
+ /**
+ * Sets the distance between consecutive base numbers.
+ * Bases whose internal number is a multiple of the period will display their base number
+ * "outside" of the secondary structure.
+ * The first base is always numbered.
+ * @param n New numbering period
+ */
+ public void setNumPeriod(int n) {
+ _numPeriod = n;
+ repaint();
+ }
+
+ public void setAutoCenter(boolean _autoCenter) {
+ this._autoCenter = _autoCenter;
+ }
+
+ public void setAutoFit(boolean fit) {
+ _autoFit = fit;
+ repaint();
+ }
+
+ void setRNA(EmbeddedRNA r) {
+ _r = r;
+ }
+
+ private Dimension getStringDimension(Graphics2D g, String s) {
+ FontMetrics fm = g.getFontMetrics();
+ Rectangle2D r = fm.getStringBounds(s, g);
+ return (new Dimension((int) r.getWidth(), (int) fm.getAscent() - fm.getDescent()));
+ }
+
+ private void drawStringCentered(Graphics2D g2, String res, double x, double y) {
+ Dimension d = getStringDimension(g2, res);
+ x -= (double) d.width / 2.0;
+ y += (double) d.height / 2.0;
+ //g2.drawRect(x, y-d.height, d.width, d.height);
+ g2.drawString(res, (int) x, (int) y);
+ }
+
+ private void drawBase(Graphics2D g2, int i, char res, RealPoint p, RealPoint center, double newRadius) {
+ //res = Character.toTitleCase(res);
+ g2.setColor(_structureSelection[i] ? BASE_INNER_COLOR_SELECTED : BASE_INNER_COLOR);
+ g2.fillOval((int) (p.x - newRadius), (int) (p.y - newRadius), (int) (2.0 * newRadius), (int) (2.0 * newRadius));
+ g2.setColor(_structureSelection[i] ? BASE_OUTLINE_COLOR_SELECTED : BASE_OUTLINE_COLOR);
+ g2.drawOval((int) (p.x - newRadius), (int) (p.y - newRadius), (int) (2 * newRadius), (int) (2 * newRadius));
+ String label = "" + res;
+ g2.setColor(_structureSelection[i] ? BASE_NAME_COLOR_SELECTED : BASE_NAME_COLOR);
+ drawStringCentered(g2, label, p.x, p.y);
+ if ((i == 0) || ((i + 1) % _numPeriod == 0)) {
+ double d1 = p.distance(center);
+ double distLabel = (d1 + 2.5 * newRadius) / d1;
+ double vx = (p.x - center.x);
+ double vy = (p.y - center.y);
+ g2.setColor(BASE_NUMBERS_COLOR);
+ drawStringCentered(g2, "" + (i + _numOffset), center.x + vx * distLabel, center.y + vy * distLabel);
+ }
+ }
+
+ private void updateBaseFontSize(int size) {
+ _baseFontSize = size;
+ _baseNameFont = Font.decode(_baseFontFamily + "-" + _baseFontStyle + "-" + _baseFontSize);
+// setFont(_baseNameFont);
+ }
+ public void fitStructure() {
+ int width = this.getWidth();
+ int height = this.getHeight();
+ int innerWidth = width - 2 * BORDER;
+ int innerHeight = height - 2 * BORDER;
+ int leftOffset = BORDER + ((width - 2 * BORDER) - innerWidth) / 2;
+ int topOffset = BORDER + ((height - 2 * BORDER) - innerHeight) / 2;
+
+
+ RealRectangle bbox = new RealRectangle(leftOffset, topOffset, innerWidth, innerHeight);
+
+
+ RealRectangle rnabbox = _rnaInitialBoundigBox;
+ _scaleFactor = Math.min((double) bbox.width / (double) rnabbox.width, (double) bbox.height / (double) rnabbox.height);
+ _initialOffset = new RealPoint();
+ _panOffset = new RealPoint();
+ _panOffsetDragging = new RealPoint();
+ _panOffsetDragBegin = new RealPoint();
+
+
+ }
+ private void renderRNA(Graphics2D g2, RealRectangle bbox) {
+ RealRectangle rnabbox = _rnaInitialBoundigBox;
+// RealRectangle rnabbox = _r.getBBox();
+ if (_autoFit || _initialAutoFit ) {
+ _initialAutoFit = false;
+ _scaleFactor = Math.min((double) bbox.width / (double) rnabbox.width, (double) bbox.height / (double) rnabbox.height);
+ }
+// double offX = _initialOffset.x;
+// double offY = _initialOffset.y;
+ double offX = bbox.x;
+ double offY = bbox.y;
+ if (_autoCenter) {
+ offX = (bbox.x + (bbox.width - Math.round(rnabbox.width * _scaleFactor)) / 2.0);
+ offY = (bbox.y + (bbox.height - Math.round(rnabbox.height * _scaleFactor)) / 2.0);
+ }
+ //g2.drawRect((int)offX,(int)offY,(int)rnabbox.width,(int)rnabbox.height);
+ double newWidth = (_scaleFactor * rnabbox.width);
+ double newHeight = (_scaleFactor * rnabbox.height);
+ double newRadius = Math.max(1.0, (_scaleFactor * EmbeddedRNA.BASE_RADIUS));
+ int newFontSize = Math.max(1, (int) ((1.7 * EmbeddedRNA.BASE_RADIUS) * _scaleFactor));
+ offX += (_panOffset.x + _panOffsetDragging.x);
+ offY += (_panOffset.y + _panOffsetDragging.y);
+
+ _offsetPanel = new RealPoint(offX, offY);
+ _offsetRNA = new RealPoint(rnabbox.x, rnabbox.y);
+
+ // Re-scaling once and for all
+ RealPoint[] newCoords = new RealPoint[_r.getSize()];
+ RealPoint[] newCenters = new RealPoint[_r.getSize()];
+ for (int i = 0; i < _r.getSize(); i++) {
+ RealPoint p = _r.getCoord(i);
+// newCoords[i] = new RealPoint(offX + (_scaleFactor * (p.x)), offY + (_scaleFactor * (p.y)));
+ newCoords[i] = new RealPoint(offX + (_scaleFactor * (p.x - rnabbox.x)), offY + (_scaleFactor * (p.y - rnabbox.y)));
+ RealPoint c = _r.getCenter(i);
+// newCenters[i] = new RealPoint(offX + (_scaleFactor * (c.x)), offY + (_scaleFactor * (c.y)));
+ newCenters[i] = new RealPoint(offX + (_scaleFactor * (c.x - rnabbox.x)), offY + (_scaleFactor * (c.y - rnabbox.y)));
+ }
+
+ // Keep track of coordinates for mouse interactions
+ _realCoords = newCoords;
+
+ updateBaseFontSize(newFontSize);
+ BasicStroke plain = new BasicStroke((int) (2.0 * _scaleFactor), BasicStroke.JOIN_ROUND, BasicStroke.CAP_ROUND);
+ BasicStroke boldStroke = new BasicStroke((int) (4.0 * _scaleFactor), BasicStroke.JOIN_ROUND, BasicStroke.CAP_ROUND);
+ BasicStroke bpStroke = new BasicStroke((int) (6.0 * _scaleFactor), BasicStroke.JOIN_ROUND, BasicStroke.CAP_ROUND);
+ //g2.setFont(_baseNameFont);
+
+ // Drawing backbone
+ g2.setColor(BACKBONE_COLOR);
+ g2.setStroke(plain);
+
+ for (int i = 1; i < _r.getSize(); i++) {
+ if (i - 1 == _hooverHelix.begin) {
+ g2.setColor(SELECTED_HELIX_COLOR);
+ g2.setStroke(boldStroke);
+ }
+ if (i - 1 == _hooverHelix.end) {
+ g2.setColor(BACKBONE_COLOR);
+ g2.setStroke(plain);
+ }
+ g2.drawLine((int) newCoords[i - 1].x, (int) newCoords[i - 1].y, (int) newCoords[i].x, (int) newCoords[i].y);
+ }
+
+ // Drawing base-pairs
+ g2.setColor(BOND_COLOR);
+ g2.setStroke(bpStroke);
+ double bpLen = 0.45;
+ if( _drawMode == DRAW_MODE_CIRCLE ) {
+ bpLen = 1;
+ }
+ for (int i = 0; i < _r.getSize(); i++) {
+ int j = _r.getBP(i);
+ if (j > i) {
+ g2.setColor(getBondColor(_r.getRes(i), _r.getRes(j)));
+ double x1 = newCoords[i].x + (newCoords[j].x - newCoords[i].x ) * bpLen ;
+ double x2 = newCoords[i].x + (newCoords[j].x - newCoords[i].x ) * ( 1 - bpLen ) ;
+ double y1 = newCoords[i].y + (newCoords[j].y - newCoords[i].y ) * bpLen ;
+ double y2 = newCoords[i].y + (newCoords[j].y - newCoords[i].y ) * ( 1 - bpLen ) ;
+ g2.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
+// g2.drawLine((int) newCoords[i].x, (int) newCoords[i].y, (int) newCoords[j].x, (int) newCoords[j].y);
+ }
+ }
+
+
+ // Drawing bases
+ g2.setStroke(plain);
+ g2.setFont(_baseNameFont);
+ for (int i = 0; i < _r.getSize(); i++) {
+ char c = _r.getRes(i);
+ drawBase(g2, i, c, newCoords[i], newCenters[i], newRadius);
+ }
+
+ // Drawing bbox
+ //g2.setColor(Color.GRAY);
+ //g2.setStroke(dashed);
+ //g2.drawRect(offX, offY, newWidth, newHeight);
+ }
+
+ private Color getBondColor(char b1, char b2) {
+ String basePair = ("" + b1).toLowerCase() + ("" + b2).toLowerCase();
+ if( "gc".equals(basePair) || "cg".equals(basePair) ) return Color.RED;
+ if( "at".equals(basePair) || "ta".equals(basePair) ) return Color.BLUE;
+ return BOND_COLOR;
+ }
+
+ @Override
+ public void paintComponent(Graphics g2) {
+ super.paintComponent(g2);
+ Graphics2D g = (Graphics2D) g2;
+ g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+ g.setColor(getBackground());
+ g.fillRect(0, 0, this.getWidth(), this.getHeight());
+
+
+ g.setColor(TITLE_COLOR);
+ int width = this.getWidth();
+ int height = this.getHeight();
+// System.out.println("width:" + width + ", height:" + height);
+ if (!_title.equals("")) {
+ g2.setFont(_titleFont);
+ drawStringCentered(g, _title, width / 2, height - TITLE_HEIGHT / 2.0);
+ height -= TITLE_HEIGHT;
+ }
+ int innerWidth = width - 2 * BORDER;
+ int innerHeight = height - 2 * BORDER;
+ int leftOffset = BORDER + ((width - 2 * BORDER) - innerWidth) / 2;
+ int topOffset = BORDER + ((height - 2 * BORDER) - innerHeight) / 2;
+
+
+ // Display outer rectangle
+ g.setColor(Color.GRAY);
+ g.setStroke(dashed);
+ //g.drawRect(leftOffset, topOffset, innerWidth, innerHeight);
+
+ // Draw RNA
+ renderRNA(g, new RealRectangle(leftOffset, topOffset, innerWidth, innerHeight));
+ }
+
+ private RealPoint panelToLogicPoint(RealPoint p) {
+ return new RealPoint(((p.x - _offsetPanel.x) / _scaleFactor) + _offsetRNA.x,
+ ((p.y - _offsetPanel.y) / _scaleFactor) + _offsetRNA.y);
+ }
+
+ private void moveSingleAtom(int index, int x, int y) {
+ if ((index >= 0) && (index < _r.getSize())) {
+ RealPoint pr = _realCoords[index];
+ RealPoint pold = _r.getCoord(index);
+ double dx = ((x - pr.x) / _scaleFactor);
+ double dy = ((y - pr.y) / _scaleFactor);
+
+ _r.setCoord(index, pold.x + dx, pold.y + dy);
+ this.repaint();
+ }
+ }
+
+ private void moveHelixAtom(int index, int x, int y) {
+ if ((index >= 0) && (index < _r.getSize())) {
+ RNASecStr r = _r.getRNASecStr();
+ int indexTo = r.getBP(index);
+ if (indexTo != -1) {
+ Range h = _r.getHelix(index);
+ Range ml = _r.getMultiLoop(h.begin);
+
+ int i = ml.begin;
+ if ((ml.begin == 0) || (ml.end == _r.getSize() - 1)) {
+ return;
+ }
+ int prevIndex = h.begin;
+ int nextIndex = h.end;
+ while (i <= ml.end) {
+ int j = _r.getBP(i);
+ if ((j != -1) && (i < h.begin)) {
+ prevIndex = i;
+ }
+ if ((j != -1) && (i > h.end) && (nextIndex == h.end)) {
+ nextIndex = i;
+ }
+ if ((j > i) && (j < ml.end)) {
+ i = _r.getBP(i);
+ } else {
+ i++;
+ }
+ }
+ RealPoint p = new RealPoint(x, y);
+ RealPoint oldPos = _r.getCoord(index);
+ RealPoint limitLoopLeft = _r.getCoord(ml.end);
+ RealPoint limitLoopRight = _r.getCoord(ml.begin);
+ RealPoint limitLeft = _r.getCoord(prevIndex);
+ RealPoint limitRight = _r.getCoord(nextIndex);
+ RealPoint helixStart = _r.getCoord(h.begin);
+ RealPoint helixStop = _r.getCoord(h.end);
+ RealPoint center = _r._em._centers[h.begin];
+ RealPoint newPos = panelToLogicPoint(p);
+ double base = (computeAngle(center, limitLoopRight) + computeAngle(center, limitLoopLeft)) / 2.0;
+ double pLimR = computeAngle(center, limitLeft) - base;
+ double pHelR = computeAngle(center, helixStart) - base;
+ double pNew = computeAngle(center, newPos) - base;
+ double pOld = computeAngle(center, oldPos) - base;
+ double pHelL = computeAngle(center, helixStop) - base;
+ double pLimL = computeAngle(center, limitRight) - base;
+ //System.out.printf("Base:%.2f => %.2f < %.2f < [%.2f,%.2f] < %.2f < %.2f\n",base, pLimR,pHelR,pNew,pOld,pHelL,pLimL);
+ if (pLimR < 0.0) {
+ pLimR += 2.0 * Math.PI;
+ }
+ if ((pHelR < 0.0) || (pHelR < pLimR)) {
+ pHelR += 2.0 * Math.PI;
+ }
+ if ((pNew < 0.0) || (pNew < pHelR)) {
+ pNew += 2.0 * Math.PI;
+ }
+ if ((pOld < 0.0) || (pOld < pHelR)) {
+ pOld += 2.0 * Math.PI;
+ }
+ if ((pHelL < 0.0) || (pHelL < pOld)) {
+ pHelL += 2.0 * Math.PI;
+ }
+ if ((pLimL < 0.0) || (pLimL < pHelL)) {
+ pLimL += 2.0 * Math.PI;
+ //System.out.printf("Corrected:%.2f => %.2f < %.2f < [%.2f,%.2f] < %.2f < %.2f\n",base, pLimR,pHelR,pNew,pOld,pHelL,pLimL);
+ }
+ double minDelta = (normalizeAngle(pHelR) - normalizeAngle(pLimR));
+ double maxDelta = normalizeAngle(pLimL) - normalizeAngle(pHelL);
+ //double maxDelta = 300;
+
+ double delta = normalizeAngle(pNew) - normalizeAngle(pOld);
+
+
+ delta = Math.max(-minDelta + 0.25, delta);
+ delta = Math.min(maxDelta - 0.25, delta);
+ rotateHelix(center, h.begin, h.end, delta);
+
+ // Re-assigns unpaired atoms
+ boolean over = false;
+ helixStart = _r.getCoord(h.begin);
+ helixStop = _r.getCoord(h.end);
+ pHelR = computeAngle(center, helixStop) - base;
+ pHelL = computeAngle(center, helixStart) - base;
+
+ i = h.begin - 1;
+ Vector nextBases = new Vector();
+ while (!over) {
+ if (i < 0) {
+ over = true;
+ } else {
+ if (_r.getBP(i) == -1) {
+ nextBases.add(new Integer(i));
+ } else {
+ over = true;
+ }
+ }
+ i--;
+ }
+ Vector prevBases = new Vector();
+ over = false;
+ i = h.end + 1;
+ while (!over) {
+ if (i >= _r.getSize()) {
+ over = true;
+ } else {
+ if (_r.getBP(i) == -1) {
+ prevBases.add(new Integer(i));
+ } else {
+ over = true;
+ }
+ }
+ i++;
+ }
+ double radius = center.distance(helixStart);
+ double anglePrev = normalizeAngle(pLimL - pHelR);
+
+ for (i = 0; i < prevBases.size(); i++) {
+ int k = prevBases.get(i).intValue();
+ double newAngle = base + pHelR + ((i + 1) * anglePrev) / (prevBases.size() + 1);
+ double newX = center.x + radius * Math.cos(newAngle);
+ double newY = center.y + radius * Math.sin(newAngle);
+ _r.setCoord(k, newX, newY);
+ }
+ double angleNext = normalizeAngle(pHelL - pLimR);
+ //System.out.println(nextBases);
+ for (i = 0; i < nextBases.size(); i++) {
+ int k = nextBases.get(i).intValue();
+ double newAngle = base + pHelL - ((i + 1) * angleNext) / (nextBases.size() + 1);
+ double newX = center.x + radius * Math.cos(newAngle);
+ double newY = center.y + radius * Math.sin(newAngle);
+ _r.setCoord(k, newX, newY);
+ }
+
+
+
+ }
+ }
+ }
+
+ private double normalizeAngle(double angle) {
+ return normalizeAngle(angle, 0.0);
+ }
+
+ private double normalizeAngle(double angle, double base) {
+ while (angle < base) {
+ angle += 2.0 * Math.PI;
+ }
+ while (angle >= (2.0 * Math.PI) - base) {
+ angle -= 2.0 * Math.PI;
+ }
+ return angle;
+ }
+
+ private double computeAngle(RealPoint center, RealPoint p) {
+ double dist = center.distance(p);
+ double angle = Math.asin((p.y - center.y) / dist);
+ if (p.x - center.x < 0) {
+ angle = Math.PI - angle;
+ }
+ return angle;
+ }
+
+ private RealPoint rotatePoint(RealPoint center, RealPoint p, double angle) {
+ double dist = p.distance(center);
+ double oldAngle = Math.asin((p.y - center.y) / dist);
+ if (p.x - center.x < 0) {
+ oldAngle = Math.PI - oldAngle;
+ }
+ double newX = (center.x + dist * Math.cos(oldAngle + angle));
+ double newY = (center.y + dist * Math.sin(oldAngle + angle));
+ return new RealPoint(newX, newY);
+ }
+
+ private void rotateHelix(RealPoint center, int i, int j, double angle) {
+
+ for (int k = i; k <= j; k++) {
+ RealPoint oldp = _r.getCoord(k);
+ RealPoint newp = rotatePoint(center, oldp, angle);
+ _r.setCoord(k, newp);
+ if ((k != i) && (k != j)) {
+ RealPoint oldc = _r._em._centers[k];
+ RealPoint newc = rotatePoint(center, oldc, angle);
+ _r._em._centers[k] = newc;
+ }
+ }
+ repaint();
+ }
+
+ /**
+ * Returns the RNA secondary structure diplayed by this panel as a well-parenthesized
+ * word, accordingly to the DBN format
+ * @return This panel's secondary structure
+ */
+ public String getStructDBN() {
+ String result = "";
+ for (int i = 0; i < _r.getSize(); i++) {
+ int j = _r.getBP(i);
+ if (j == -1) {
+ result += ".";
+ } else if (i > j) {
+ result += ")";
+ } else {
+ result += "(";
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the raw nucleotides sequence for the displayed RNA
+ * @return The RNA sequence
+ */
+ public String getSeq() {
+ String result = "";
+ for (int i = 0; i < _r.getSize(); i++) {
+ result += _r.getRes(i);
+ }
+ return result;
+ }
+
+ /**
+ * Returns the color used to draw backbone bounds.
+ * @return The color used to draw backbone bounds
+ */
+ public Color getBackboneColor() {
+ return BACKBONE_COLOR;
+ }
+
+ /**
+ * Sets the color to be used for drawing backbone interactions.
+ * @param backbone_color The new color for the backbone bounds
+ */
+ public void setBackboneColor(Color backbone_color) {
+ BACKBONE_COLOR = backbone_color;
+ }
+
+ /**
+ * Returns the color to be used for displaying the inner part of bases.
+ * @return The color for the inner part of bases
+ */
+ public Color getBaseInnerColor() {
+ return BASE_INNER_COLOR;
+ }
+
+ /**
+ * Sets the color to be used for displaying the inner part of bases.
+ * @param base_inner_color The new color for the inner part of bases
+ */
+ public void setBaseInnerColor(Color base_inner_color) {
+ BASE_INNER_COLOR = base_inner_color;
+ }
+
+ /**
+ * Returns the color to be used for drawing nucleotide names.
+ * @return The color for nucleotide names
+ */
+ public Color getBaseNameColor() {
+ return BASE_NAME_COLOR;
+ }
+
+ /**
+ * Sets the color to be used for drawing nucleotide names.
+ * @param base_name_color The new color for nucleotide names
+ */
+ public void setBaseNameColor(Color base_name_color) {
+ BASE_NAME_COLOR = base_name_color;
+ }
+
+ /**
+ * Returns the color to be used for displaying nucleotides numbers.
+ * @return The color of nucleotide numbers
+ */
+ public Color getBaseNumbersColor() {
+ return BASE_NUMBERS_COLOR;
+ }
+
+ /**
+ * Sets the color to be used for displaying nucleotides numbers.
+ * @param base_numbers_color The new color of nucleotide numbers
+ */
+ public void setBaseNumbersColor(Color base_numbers_color) {
+ BASE_NUMBERS_COLOR = base_numbers_color;
+ }
+
+ /**
+ * Returns the color used to display the external part of nucleotides (external circle).
+ * @return The color used to display the external part of nucleotides
+ */
+ public Color getBaseOutlineColor() {
+ return BASE_OUTLINE_COLOR;
+ }
+
+ /**
+ * Sets the new color used to display the external part of nucleotides (external circle).
+ * @param base_outline_color The new color of the external nucleotides circle
+ */
+ public void setBaseOutlineColor(Color base_outline_color) {
+ BASE_OUTLINE_COLOR = base_outline_color;
+ }
+
+ /**
+ * Returns the color used to display hydrogen bonds (base pairings)
+ * @return The color of hydrogen bonds
+ */
+ public Color getBondColor() {
+ return BOND_COLOR;
+ }
+
+ /**
+ * Returns the title of this panel
+ * @return The title
+ */
+ public String getTitle() {
+ return _title;
+ }
+
+ /**
+ * Sets the new color to be used for hydrogen bonds (base pairings)
+ * @param bond_color The new color for hydrogen bonds
+ */
+ public void setBondColor(Color bond_color) {
+ BOND_COLOR = bond_color;
+ }
+
+ /**
+ * Sets the size of the border, i.e. the empty space between the end of the drawing area
+ * and the actual border.
+ * @param b The new border size
+ */
+ public void setBorderSize(int b) {
+ BORDER = b;
+ }
+
+ /**
+ * Returns the size of the border, i.e. the empty space between the end of the drawing area
+ * @return The border size
+ */
+ public int getBorderSize() {
+ return BORDER;
+ }
+
+ /**
+ * Recomputes the layout of the secondary structure, using a previously set
+ * drawing strategy.
+ * @see #DRAW_MODE_CIRCLE
+ * @see #DRAW_MODE_RADIATE
+ */
+ public void redoLayout() {
+ setRNA(new String(_r._str._seq), _r._str.getStructDBN());
+ }
+
+ /**
+ * Recomputes the layout of the secondary structure. The result will
+ * depend on the chosen drawing strategy.
+ * @param drawMode The drawing strategy
+ * @see #DRAW_MODE_CIRCLE
+ * @see #DRAW_MODE_RADIATE
+ */
+ public void redoLayout(int drawMode) {
+ _drawMode = drawMode;
+ setRNA(new String(_r._str._seq), _r._str.getStructDBN());
+ }
+
+ private void buildPopupMenu() {
+ // Reset menuitem
+ JMenuItem redisplay = new JMenuItem("Reset");
+ redisplay.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ reset();
+ }
+ });
+
+ // Drawing algorithm menu
+ JMenu submenuAlgo = new JMenu("Redraw");
+ JMenuItem algoCircle = new JMenuItem("Circular");
+ algoCircle.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ setRNA(_r._str, VARNAPanel.DRAW_MODE_CIRCLE);
+ }
+ });
+ JMenuItem algoRadiate = new JMenuItem("Radiate");
+ algoRadiate.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ setRNA(_r._str, VARNAPanel.DRAW_MODE_RADIATE);
+ }
+ });
+ submenuAlgo.add(algoCircle);
+ submenuAlgo.add(algoRadiate);
+
+ // Export menu
+ JMenu submenuExport = new JMenu("Export");
+ JMenu submenuExportStructure = new JMenu("Structure");
+ JMenu submenuExportImage = new JMenu("Image");
+ JMenuItem exportDBN = new JMenuItem("DBN (dotbracket) Format");
+ exportDBN.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIExportDBN();
+ }
+ });
+ JMenuItem exportBPSEQ = new JMenuItem("BPSEQ Format");
+ exportDBN.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIExportBPSEQ();
+ }
+ });
+ JMenuItem exportCT = new JMenuItem("CT Format");
+ exportDBN.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIExportCT();
+ }
+ });
+ JMenuItem exportEPS = new JMenuItem("EPS Picture");
+ exportEPS.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIExportEPS();
+ }
+ });
+ JMenuItem exportXFIG = new JMenuItem("XFIG File");
+ exportXFIG.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIExportXFIG();
+ }
+ });
+ JMenuItem exportSVG = new JMenuItem("SVG File");
+ exportSVG.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIExportSVG();
+ }
+ });
+ JMenuItem exportJPEG = new JMenuItem("JPEG Picture");
+ exportJPEG.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIExportJPEG();
+ }
+ });
+
+ submenuExport.add(submenuExportImage);
+ submenuExport.add(submenuExportStructure);
+ submenuExportStructure.add(exportDBN);
+ submenuExportStructure.add(exportCT);
+ submenuExportStructure.add(exportBPSEQ);
+ submenuExportImage.add(exportSVG);
+ submenuExportImage.add(exportEPS);
+ submenuExportImage.add(exportXFIG);
+ submenuExportImage.add(exportJPEG);
+
+ // Input menu
+ JMenu submenuImport = new JMenu("Open");
+ JMenuItem manualInput = new JMenuItem("User input");
+ manualInput.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIManualInput();
+ }
+ });
+ JMenuItem diskInput = new JMenuItem("File");
+ diskInput.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIFileInput();
+ }
+ });
+
+ submenuImport.add(diskInput);
+ submenuImport.add(manualInput);
+
+ // Input menu
+ JMenu submenuDisplay = new JMenu("Display");
+ JMenu colorsDisplay = new JMenu("Colors");
+ JMenuItem backgroundDisplay = new JMenuItem("Background");
+ backgroundDisplay.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIBackgroundDisplay();
+ }
+ });
+ JMenuItem baseInnerDisplay = new JMenuItem("Bases inner");
+ baseInnerDisplay.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIBaseInnerDisplay();
+ }
+ });
+ JMenuItem baseOuterDisplay = new JMenuItem("Bases outer");
+ baseOuterDisplay.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIBaseOuterDisplay();
+ }
+ });
+ JMenuItem backboneDisplay = new JMenuItem("Backbone");
+ backboneDisplay.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIBackboneColorDisplay();
+ }
+ });
+ JMenuItem bondsDisplay = new JMenuItem("Bonds");
+ bondsDisplay.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIBondsDisplay();
+ }
+ });
+ JMenu fontsDisplay = new JMenu("Fonts");
+ JMenuItem titleDisplay = new JMenuItem("Title");
+ titleDisplay.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UITitleDisplay();
+ }
+ });
+ JMenuItem baseDisplay = new JMenuItem("Bases");
+ baseDisplay.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIBaseDisplay();
+ }
+ });
+ JMenuItem titleContentDisplay = new JMenuItem("Title");
+ titleContentDisplay.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UITitleContentDisplay();
+ }
+ });
+ JMenuItem borderDisplay = new JMenuItem("Border Size");
+ borderDisplay.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UIBorderDisplay();
+ }
+ });
+ JMenuItem numPeriodDisplay = new JMenuItem("Num Period");
+ numPeriodDisplay.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ UINumPeriod();
+ }
+ });
+
+ JMenuItem aboutBox = new JMenuItem("About");
+ aboutBox.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent arg0) {
+ AboutDialog aboutDialog = new AboutDialog(null, true);
+ aboutDialog.setVisible(true);
+ }
+ });
+
+ colorsDisplay.add(backgroundDisplay);
+ colorsDisplay.add(backboneDisplay);
+ colorsDisplay.add(baseInnerDisplay);
+ colorsDisplay.add(baseOuterDisplay);
+ colorsDisplay.add(bondsDisplay);
+ fontsDisplay.add(titleDisplay);
+ fontsDisplay.add(baseDisplay);
+ submenuDisplay.add(colorsDisplay);
+ submenuDisplay.add(fontsDisplay);
+ submenuDisplay.add(titleContentDisplay);
+ submenuDisplay.add(borderDisplay);
+ submenuDisplay.add(numPeriodDisplay);
+
+ popup.add(submenuImport);
+ popup.add(submenuExport);
+ popup.addSeparator();
+ popup.add(submenuAlgo);
+ popup.addSeparator();
+ popup.add(submenuDisplay);
+ popup.addSeparator();
+
+ popup.add(aboutBox);
+ //popup.add(redisplay);
+ this.add(popup);
+ }
+
+ private void UIBaseDisplay() {
+ String family = selectFont("Base font", "Please select a new font for bases:", this.getFont());
+ setBaseFontFamily(family);
+ }
+
+ private void UITitleDisplay() {
+ String family = selectFont("Title font", "Please select a new font for the title:", this.getFont());
+ setTitleFontFamily(family);
+ }
+
+ private String selectFont(String title, String message, Font defaultFont) {
+ GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
+ String[] polices = ge.getAvailableFontFamilyNames();
+ JLabel msg = new JLabel(message);
+ JComboBox l = new JComboBox(polices);
+ JPanel p = new JPanel();
+ p.setLayout(new GridLayout(1, 2));
+ p.add(l);
+ p.add(msg);
+ JOptionPane.showConfirmDialog(this, l, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
+ return (String) l.getSelectedItem();
+ }
+
+ private void UIBaseOuterDisplay() {
+ Color c = JColorChooser.showDialog(this, "Choose new base outline color", this.getBackground());
+ if (c != null) {
+ this.setBaseOutlineColor(c);
+ }
+ }
+
+ private void UIBaseInnerDisplay() {
+ Color c = JColorChooser.showDialog(this, "Choose new base filling color", this.getBackground());
+ if (c != null) {
+ this.setBaseInnerColor(c);
+ }
+ }
+
+ private void UIBackboneColorDisplay() {
+ Color c = JColorChooser.showDialog(this, "Choose new backbone color", this.getBackground());
+ if (c != null) {
+ this.setBackboneColor(c);
+ }
+ }
+
+ private void UIBondsDisplay() {
+ Color c = JColorChooser.showDialog(this, "Choose new bonds color", this.getBackground());
+ if (c != null) {
+ this.setBondColor(c);
+ }
+ }
+
+ private void UIBackgroundDisplay() {
+ Color c = JColorChooser.showDialog(this, "Choose new background color", this.getBackground());
+ if (c != null) {
+ this.setBackground(c);
+ }
+ }
+
+ private void UIExportDBN() {
+ JFileChooser fc = new JFileChooser();
+ if (fc.showSaveDialog(VARNAPanel.this) == JFileChooser.APPROVE_OPTION) {
+ _r._str.exportDBN(fc.getSelectedFile().getAbsolutePath(), this._title);
+ }
+ }
+
+ private void UIExportBPSEQ() {
+ JFileChooser fc = new JFileChooser();
+ if (fc.showSaveDialog(VARNAPanel.this) == JFileChooser.APPROVE_OPTION) {
+ _r._str.exportBPSEQ(fc.getSelectedFile().getAbsolutePath(), this._title);
+ }
+ }
+
+ private void UIExportCT() {
+ JFileChooser fc = new JFileChooser();
+ if (fc.showSaveDialog(VARNAPanel.this) == JFileChooser.APPROVE_OPTION) {
+ _r._str.exportCT(fc.getSelectedFile().getAbsolutePath(), this._title);
+ }
+ }
+
+ private void UIExportEPS() {
+ JFileChooser fc = new JFileChooser();
+ if (fc.showSaveDialog(VARNAPanel.this) == JFileChooser.APPROVE_OPTION) {
+ _r.saveEmbeddedRNAEPS(fc.getSelectedFile().getAbsolutePath(), _title, _numPeriod);
+ }
+ }
+
+ private void UIExportXFIG() {
+ JFileChooser fc = new JFileChooser();
+ if (fc.showSaveDialog(VARNAPanel.this) == JFileChooser.APPROVE_OPTION) {
+ _r.saveEmbeddedRNAXFIG(fc.getSelectedFile().getAbsolutePath(), _title, _numPeriod);
+ }
+ }
+
+ private void UIExportSVG() {
+ JFileChooser fc = new JFileChooser();
+ fc.setDialogType(JFileChooser.SAVE_DIALOG);
+ if (fc.showSaveDialog(VARNAPanel.this) == JFileChooser.APPROVE_OPTION) {
+// _r.saveEmbeddedRNASVG(fc.getSelectedFile().getAbsolutePath(), _title, _numPeriod, );
+ saveToSVG(fc.getSelectedFile().getAbsolutePath());
+ }
+ }
+
+ private void UIExportJPEG() {
+ JFileChooser fc = new JFileChooser();
+ if (fc.showSaveDialog(VARNAPanel.this) == JFileChooser.APPROVE_OPTION) {
+ saveToJPEG(fc.getSelectedFile().getAbsolutePath());
+ }
+ }
+
+ private void UIFileInput() {
+ JFileChooser fc = new JFileChooser();
+ if (fc.showOpenDialog(VARNAPanel.this) == JFileChooser.APPROVE_OPTION) {
+ RNASecStr s = RNASecStr.loadSecStr(fc.getSelectedFile().getAbsolutePath());
+ setRNA(s);
+ }
+
+ }
+
+ private void UIManualInput() {
+ JPanel p = new JPanel();
+ JPanel pup = new JPanel();
+ JPanel pdown = new JPanel();
+ p.setLayout(new GridLayout(2, 1));
+ pup.setLayout(new FlowLayout(FlowLayout.LEFT));
+ pdown.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+ Font _textFieldsFont = Font.decode("MonoSpaced-PLAIN-12");
+
+ JLabel lseq = new JLabel("Sequence: ");
+ JTextField tseq = new JTextField(getSeq());
+ JLabel lstr = new JLabel("Structure: ");
+ JTextField tstr = new JTextField(this.getStructDBN());
+ tstr.setPreferredSize(new Dimension(400, tstr.getPreferredSize().height));
+ tseq.setPreferredSize(new Dimension(400, tseq.getPreferredSize().height));
+ tstr.setFont(_textFieldsFont);
+ tseq.setFont(_textFieldsFont);
+ pup.add(lseq);
+ pup.add(tseq);
+ pdown.add(lstr);
+ pdown.add(tstr);
+ p.add(pup);
+ p.add(pdown);
+ if (JOptionPane.showConfirmDialog(this, p, "Input sequence/structure", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
+ setRNA(tseq.getText(), tstr.getText());
+ }
+ }
+
+ private void UINumPeriod() {
+ JSpinner numSpinner = new JSpinner(new SpinnerNumberModel(_numPeriod, 1, (_r.getSize()) / 2, 1));
+ if (JOptionPane.showConfirmDialog(this, numSpinner, "Set new numbering period", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
+ this.setNumPeriod((Integer) numSpinner.getModel().getValue());
+ }
+// JSlider numPeriodSlider = new JSlider(JSlider.HORIZONTAL, 1, (_r.getSize()) / 2, _numPeriod);
+ //Turn on labels at major tick marks.
+// numPeriodSlider.setMajorTickSpacing(10);
+// numPeriodSlider.setMinorTickSpacing(5);
+// numPeriodSlider.setPaintTicks(true);
+// numPeriodSlider.setPaintLabels(true);
+// if (JOptionPane.showConfirmDialog(this, numPeriodSlider, "Set new numbering period", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
+// this.setNumPeriod(numPeriodSlider.getValue());
+// }
+ }
+
+ private void UIBorderDisplay() {
+ JSlider borderSlider = new JSlider(JSlider.HORIZONTAL, 10, 10 + (getWidth() - 10) / 2, BORDER);
+ //Turn on labels at major tick marks.
+ borderSlider.setMajorTickSpacing(50);
+ borderSlider.setMinorTickSpacing(10);
+ borderSlider.setPaintTicks(true);
+ borderSlider.setPaintLabels(true);
+ if (JOptionPane.showConfirmDialog(this, borderSlider, "Set new border size", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
+ this.setBorderSize(borderSlider.getValue());
+ }
+ }
+
+ private void UITitleContentDisplay() {
+ String res = JOptionPane.showInputDialog(this, "Input title", this.getTitle());
+ if (res != null) {
+ this.setTitle(res);
+ }
+ }
+
+ public void saveToJPEG(String filename) {
+ Dimension size = getSize();
+ BufferedImage myImage =
+ new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
+ Graphics2D g2 = myImage.createGraphics();
+ this.paint(g2);
+ try {
+ OutputStream out = new FileOutputStream(filename);
+ JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
+ encoder.encode(myImage);
+ out.close();
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+ }
+
+// public void saveToSVG(String filename) {
+// saveToSVG(filename, 1.0);
+// }
+
+ public void saveToSVG(String filename, double scale) {
+ RealRectangle rnabbox = _r.getBBox();
+ int width = getWidth() - 2 * BORDER;
+ int height = getHeight() - 2 * BORDER;
+ double scaleFactor = Math.min((double) width / (double) rnabbox.width, (double) height / (double) rnabbox.height);
+
+ int newHeight = (int) ((double) rnabbox.height / (double) (height + BORDER) * (double) getHeight());
+// _r.saveEmbeddedRNASVG(filename, _title, _numPeriod, scaleFactor * scale, getWidth(), getHeight() );
+ _r.saveEmbeddedRNASVG(filename, _title, _numPeriod, _numOffset, scaleFactor * scale, getWidth(), newHeight );
+ }
+ /**
+ * Save to SVG 1:1 (no scaling according to panel size)
+ * @param filename
+ */
+ public void saveToSVG(String filename) {
+ RealRectangle rnabbox = _r.getBBox();
+ int width = getWidth() - 2 * BORDER;
+ int height = getHeight() - 2 * BORDER;
+ double scaleFactor = Math.min((double) width / (double) rnabbox.width, (double) height / (double) rnabbox.height);
+
+ int newHeight = (int) ((double) rnabbox.height / (double) (height + BORDER) * (double) getHeight());
+// _r.saveEmbeddedRNASVG(filename, _title, _numPeriod, scaleFactor * scale, getWidth(), getHeight() );
+ saveEmbeddedRNASVG(filename, _title, _numPeriod, _numOffset, 1.0, getWidth(), newHeight );
+
+
+ }
+
+ public void saveEmbeddedRNASVG(String path, String title, int freqNumbers, int numOffset, double scale, int width, int height) {
+ SVGExport svgExport = new SVGExport();
+ svgExport.setBoundingBox( (long) width, (long) height );
+// saveEmbeddedRNA(path, title, freqNumbers, numOffset, scale, out);
+
+ try {
+ svgExport.setScale(scale);
+
+ // Computing bounding boxes
+ double EPSMargin = 40;
+ double minX = Double.MAX_VALUE;
+ double maxX = Double.MIN_VALUE;
+ double minY = Double.MAX_VALUE;
+ double maxY = Double.MIN_VALUE;
+ for (int i = 0; i < _r._em._coords.length; i++) {
+ minX = Math.min(minX, (_r._em._coords[i].x - EmbeddedRNA.BASE_RADIUS - EPSMargin));
+ minY = Math.min(minY, -(_r._em._coords[i].y - EmbeddedRNA.BASE_RADIUS - EPSMargin));
+ maxX = Math.max(maxX, (_r._em._coords[i].x + EmbeddedRNA.BASE_RADIUS + EPSMargin));
+ maxY = Math.max(maxY, -(_r._em._coords[i].y + EmbeddedRNA.BASE_RADIUS + EPSMargin));
+ }
+
+// out.setBoundingBox( (long) (maxX-minX), (long) (maxY-minY) );
+// out.setBoundingBox( (long) getBBox().width, (long) getBBox().height );
+
+ // Drawing backbone
+ for (int i = 1; i < _r._em._coords.length; i++) {
+ long x0 = (long) (_r._em._coords[i - 1].x - minX);
+ long y0 = -(long) (_r._em._coords[i - 1].y - minY);
+ long x1 = (long) (_r._em._coords[i].x - minX);
+ long y1 = -(long) (_r._em._coords[i].y - minY);
+ svgExport.drawLine(x0, y0, x1, y1, 1);
+ }
+
+ // Drawing bonds
+ for (int i = 0; i < _r._em._coords.length; i++) {
+ if (_r._str._str[i] > i) {
+ double x0 = (_r._em._coords[i].x - minX);
+ double y0 = -(_r._em._coords[i].y - minY);
+ double x1 = (_r._em._coords[_r._str._str[i]].x - minX);
+ double y1 = -(_r._em._coords[_r._str._str[i]].y - minY);
+ double dx = x1 - x0;
+ double dy = y1 - y0;
+ double norm = Math.sqrt(dx * dx + dy * dy);
+ dx /= norm;
+ dy /= norm;
+ if (_r._em._style == VARNAPanel.DRAW_MODE_CIRCLE) {
+ svgExport.drawLine((long) x0, (long) y0, (long) x1, (long) y1, 1);
+ } else if (_r._em._style == VARNAPanel.DRAW_MODE_RADIATE) {
+ int j = _r.getBP(i);
+ Color bondColor = getBondColor(_r.getRes(i), _r.getRes(j));
+ svgExport.drawLine(
+ (long) (x0 + 1.8 * EmbeddedRNA.BASE_RADIUS * dx),
+ (long) (y0 + 1.8 * EmbeddedRNA.BASE_RADIUS * dy),
+ (long) (x1 - 1.8 * EmbeddedRNA.BASE_RADIUS * dx),
+ (long) (y1 - 1.8 * EmbeddedRNA.BASE_RADIUS * dy),
+ 4, bondColor);
+ }
+ }
+ }
+
+// double bpLen = 0.45;
+// for (int i = 0; i < _r.getSize(); i++) {
+// int j = _r.getBP(i);
+// if (j > i) {
+// g2.setColor(getBondColor(_r.getRes(i), _r.getRes(j)));
+// double x1 = newCoords[i].x + (newCoords[j].x - newCoords[i].x ) * bpLen ;
+// double x2 = newCoords[i].x + (newCoords[j].x - newCoords[i].x ) * ( 1 - bpLen ) ;
+// double y1 = newCoords[i].y + (newCoords[j].y - newCoords[i].y ) * bpLen ;
+// double y2 = newCoords[i].y + (newCoords[j].y - newCoords[i].y ) * ( 1 - bpLen ) ;
+// g2.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
+// // g2.drawLine((int) newCoords[i].x, (int) newCoords[i].y, (int) newCoords[j].x, (int) newCoords[j].y);
+// }
+// }
+
+
+ // Drawing Bases
+ long baseFontSize = (long) (1.5 * EmbeddedRNA.BASE_RADIUS);
+ svgExport.setFont(PSExport.FONT_HELVETICA_BOLD, baseFontSize);
+ for (int i = 0; i < _r._em._coords.length; i++) {
+ long x = (long) (_r._em._coords[i].x - minX);
+ long y = -(long) (_r._em._coords[i].y - minY);
+
+// svgExport.fillCircle(x, y, EmbeddedRNA.BASE_RADIUS, 1l, 0.95);
+// svgExport.drawCircle(x, y, EmbeddedRNA.BASE_RADIUS, 1l);
+ Color fillColor = _structureSelection[i] ? BASE_INNER_COLOR_SELECTED : BASE_INNER_COLOR;
+ Color strokeColor = _structureSelection[i] ? BASE_OUTLINE_COLOR_SELECTED : BASE_OUTLINE_COLOR;
+ Color textColor = _structureSelection[i] ? BASE_NAME_COLOR_SELECTED : BASE_NAME_COLOR;
+
+ svgExport.fillCircle(x, y, EmbeddedRNA.BASE_RADIUS, 1l, strokeColor, fillColor );
+ svgExport.drawText(x, y, "" + _r._str._seq[i], baseFontSize, textColor);
+ }
+
+ // Drawing base numbers
+ long numFontSize = (long) (1.5 * EmbeddedRNA.BASE_RADIUS);
+ svgExport.setFont(PSExport.FONT_HELVETICA_BOLD, numFontSize);
+
+ for (int i = 0; i < _r._em._coords.length; i++) {
+ if ((i == 0) || ((i + 1) % freqNumbers == 0)) {
+ double x0 = (_r._em._coords[i].x - minX);
+ double y0 = -(_r._em._coords[i].y - minY);
+ double x1 = (_r._em._centers[i].x - minX);
+ double y1 = -(_r._em._centers[i].y - minY);
+ double dx = x1 - x0;
+ double dy = y1 - y0;
+ double norm = Math.sqrt(dx * dx + dy * dy);
+ dx /= norm;
+ dy /= norm;
+ svgExport.drawLine((long) (x0 - 1.5 * EmbeddedRNA.BASE_RADIUS * dx), (long) (y0 - 1.5 * EmbeddedRNA.BASE_RADIUS * dy), (long) (x0 - 2.5 * EmbeddedRNA.BASE_RADIUS * dx), (long) (y0 - 2.5 * EmbeddedRNA.BASE_RADIUS * dy), 1);
+ svgExport.drawText((long) (x0 - 4 * EmbeddedRNA.BASE_RADIUS * dx), (long) (y0 - 4 * EmbeddedRNA.BASE_RADIUS * dy), "" + (i + numOffset), numFontSize);
+ }
+ }
+
+
+ FileWriter fout = new FileWriter(path);
+ fout.write(svgExport.export());
+ fout.close();
+ } catch (Exception e) {
+ }
+
+ }
+}
diff -U 3 -H -d -r -N -- original_varna_2.0/varna/export/PSExport.java src/varna/export/PSExport.java
--- original_varna_2.0/varna/export/PSExport.java 2008-01-12 00:47:00.000000000 +0100
+++ src/varna/export/PSExport.java 2008-05-13 23:55:37.000000000 +0200
@@ -7,255 +7,225 @@
* @author ponty
*
*/
-public class PSExport implements SecStrDrawingProducer{
- StringBuffer _s = new StringBuffer();
- long minX = Long.MAX_VALUE;
- long minY = Long.MAX_VALUE;
- long maxX = Long.MIN_VALUE;
- long maxY = Long.MIN_VALUE;
- double scale = 1.0;
-
- private void updateBoundingBox(long x, long y, long w, long h)
- {
- maxX = Math.max(maxX, x+w);
- minX = Math.min(minX, x);
- maxY = Math.max(maxY, y+h);
- minY = Math.min(minY, y);
- }
-
- private String PSMacros()
- {
- String setFontSize =
- // Params [fontsize|...]
- "/setbasefont \n"+
- "{ /Helvetica-Bold findfont\n"+ // => [font|scale|...]
- " exch scalefont\n"+ // => [scaled_font|...]
- " setfont \n"+ // => [...]
- " } def\n";
-
- String writeTextCentered =
- // Params [txt|size|...]
- "/txtcenter \n"+
- "{ dup \n"+ // => [txt|txt|size|...]
- " stringwidth pop\n"+ // => [wtxt|txt|size|...]
- " 2 div neg \n"+ // => [-wtxt/2|txt|size|...]
- " 3 -1 roll \n"+ // => [size|-wtxt/2|txt...]
- " 2 div neg\n"+ // => [-size/2|-wtxt/2|txt|...]
- " rmoveto\n"+ // => [txt|...]
- " show\n"+ // => [...]
- " } def\n";
- return setFontSize+writeTextCentered;
- }
+public class PSExport implements SecStrDrawingProducer {
- private String EPSHeader()
- {
- String bbox = PSBBox();
- String macros = PSMacros();
- return bbox + macros;
- }
+ StringBuffer _s = new StringBuffer();
+ long minX = Long.MAX_VALUE;
+ long minY = Long.MAX_VALUE;
+ long maxX = Long.MIN_VALUE;
+ long maxY = Long.MIN_VALUE;
+ double scale = 1.0;
- private String EPSFooter()
- {
- String showpage = "showpage\n";
- return showpage;
- }
-
-
- private void PSNewPath()
- {
- _s.append("newpath\n");
- }
+ private void updateBoundingBox(long x, long y, long w, long h) {
+ maxX = Math.max(maxX, x + w);
+ minX = Math.min(minX, x);
+ maxY = Math.max(maxY, y + h);
+ minY = Math.min(minY, y);
+ }
- private void PSMoveTo(long x, long y)
- {
- _s.append(""+x+" "+y+" moveto\n");
- }
+ private String PSMacros() {
+ String setFontSize =
+ // Params [fontsize|...]
+ "/setbasefont \n" +
+ "{ /Helvetica-Bold findfont\n" + // => [font|scale|...]
+ " exch scalefont\n" + // => [scaled_font|...]
+ " setfont \n" + // => [...]
+ " } def\n";
- private void PSLineTo(long dx, long dy)
- {
- _s.append(""+dx+" "+dy+" lineto\n");
- }
-
- private void PSRLineTo(long dx, long dy)
- {
- _s.append(""+dx+" "+dy+" rlineto\n");
- }
+ String writeTextCentered =
+ // Params [txt|size|...]
+ "/txtcenter \n" +
+ "{ dup \n" + // => [txt|txt|size|...]
+ " stringwidth pop\n" + // => [wtxt|txt|size|...]
+ " 2 div neg \n" + // => [-wtxt/2|txt|size|...]
+ " 3 -1 roll \n" + // => [size|-wtxt/2|txt...]
+ " 2 div neg\n" + // => [-size/2|-wtxt/2|txt|...]
+ " rmoveto\n" + // => [txt|...]
+ " show\n" + // => [...]
+ " } def\n";
+ return setFontSize + writeTextCentered;
+ }
- private void PSSetLineWidth(long thickness)
- {
- _s.append(""+thickness+" setlinewidth\n");
- }
+ private String EPSHeader() {
+ String bbox = PSBBox();
+ String macros = PSMacros();
+ return bbox + macros;
+ }
- private void PSStroke()
- {
- _s.append("stroke\n");
- }
+ private String EPSFooter() {
+ String showpage = "showpage\n";
+ return showpage;
+ }
- private void PSArc(long x, long y, long radius, long angleFrom, long angleTo)
- {
- _s.append(""+x+" "+y+" "+radius+" "+angleFrom+" "+angleTo+" arc\n");
- }
+ private void PSNewPath() {
+ _s.append("newpath\n");
+ }
- private String PSBBox()
- {
- return ("%%BoundingBox: "+minX+" "+minY+" "+maxX+" "+maxY+"\n");
- }
+ private void PSMoveTo(long x, long y) {
+ _s.append("" + x + " " + y + " moveto\n");
+ }
- private void PSText(String txt)
- {
- _s.append("("+txt+")\n");
- }
+ private void PSLineTo(long dx, long dy) {
+ _s.append("" + dx + " " + dy + " lineto\n");
+ }
- private void PSShow()
- {
- _s.append("show\n");
- }
+ private void PSRLineTo(long dx, long dy) {
+ _s.append("" + dx + " " + dy + " rlineto\n");
+ }
- private void PSClosePath()
- {
- _s.append("show\n");
- }
+ private void PSSetLineWidth(long thickness) {
+ _s.append("" + thickness + " setlinewidth\n");
+ }
- private void PSFill()
- {
- _s.append("fill\n");
- }
+ private void PSStroke() {
+ _s.append("stroke\n");
+ }
- private void PSSetGray(double level)
- {
- _s.append(""+level+" setgray\n");
- }
+ private void PSArc(long x, long y, long radius, long angleFrom, long angleTo) {
+ _s.append("" + x + " " + y + " " + radius + " " + angleFrom + " " + angleTo + " arc\n");
+ }
-
+ private String PSBBox() {
+ return ("%%BoundingBox: " + minX + " " + minY + " " + maxX + " " + maxY + "\n");
+ }
- private String fontName(int font)
- {
- switch(font)
- {
- case (FONT_TIMES_ROMAN):
- return "/Times-Roman";
- case (FONT_TIMES_BOLD):
- return "/Times-Bold";
- case (FONT_TIMES_ITALIC):
- return "/Times-Italic";
- case (FONT_TIMES_BOLD_ITALIC):
- return "/Times-BoldItalic";
- case (FONT_HELVETICA):
- return "/Helvetica";
- case (FONT_HELVETICA_BOLD):
- return "/Helvetica-Bold";
- case (FONT_HELVETICA_OBLIQUE):
- return "/Helvetica-Oblique";
- case (FONT_HELVETICA_BOLD_OBLIQUE):
- return "/Helvetica-BoldOblique";
- case (FONT_COURIER):
- return "/Courier";
- case (FONT_COURIER_BOLD):
- return "/Courier-Bold";
- case (FONT_COURIER_OBLIQUE):
- return "/Courier-Oblique";
- case (FONT_COURIER_BOLD_OBLIQUE):
- return "/Courier-BoldOblique";
- }
- return "/Helvetica";
- }
+ private void PSText(String txt) {
+ _s.append("(" + txt + ")\n");
+ }
- private void PSSetFont(int font,long size)
- {
- size *= scale;
- _s.append(fontName(font)+" findfont "+size+" scalefont setfont\n");
- }
+ private void PSShow() {
+ _s.append("show\n");
+ }
- public void setFont(int font,long size)
- {
- PSSetFont(font,size);
- }
+ private void PSClosePath() {
+ _s.append("show\n");
+ }
- public void drawLine(long x0, long y0, long x1, long y1, long thickness)
- {
- x0 *= scale;
- y0 *= scale;
- x1 *= scale;
- y1 *= scale;
- PSMoveTo(x0,y0);
- PSLineTo(x1,y1);
- PSSetLineWidth(thickness);
- PSStroke();
- }
+ private void PSFill() {
+ _s.append("fill\n");
+ }
-
- public void drawText(long x, long y, String txt, long height)
- {
- x *= scale;
- y *= scale;
- PSMoveTo(x,y);
- _s.append(""+(height-5)+" \n");
- PSText(txt);
- _s.append(" txtcenter\n");
- }
+ private void PSSetGray(double level) {
+ _s.append("" + level + " setgray\n");
+ }
- public void drawRectangle(long x,long y, long w, long h, long thickness)
- {
- x *= scale;
- y *= scale;
- w *= scale;
- h *= scale;
- updateBoundingBox(x,y,w,h);
- PSNewPath();
- PSMoveTo(x,y);
- PSRLineTo(0,w);
- PSRLineTo(h,0);
- PSRLineTo(0,-w);
- PSRLineTo(-h,0);
- PSClosePath();
- PSSetLineWidth(thickness);
- PSStroke();
- }
+ private String fontName(int font) {
+ switch (font) {
+ case (FONT_TIMES_ROMAN):
+ return "/Times-Roman";
+ case (FONT_TIMES_BOLD):
+ return "/Times-Bold";
+ case (FONT_TIMES_ITALIC):
+ return "/Times-Italic";
+ case (FONT_TIMES_BOLD_ITALIC):
+ return "/Times-BoldItalic";
+ case (FONT_HELVETICA):
+ return "/Helvetica";
+ case (FONT_HELVETICA_BOLD):
+ return "/Helvetica-Bold";
+ case (FONT_HELVETICA_OBLIQUE):
+ return "/Helvetica-Oblique";
+ case (FONT_HELVETICA_BOLD_OBLIQUE):
+ return "/Helvetica-BoldOblique";
+ case (FONT_COURIER):
+ return "/Courier";
+ case (FONT_COURIER_BOLD):
+ return "/Courier-Bold";
+ case (FONT_COURIER_OBLIQUE):
+ return "/Courier-Oblique";
+ case (FONT_COURIER_BOLD_OBLIQUE):
+ return "/Courier-BoldOblique";
+ }
+ return "/Helvetica";
+ }
- public void drawCircle(long x,long y, long radius, long thickness)
- {
- x *= scale;
- y *= scale;
- radius *= scale;
- updateBoundingBox(x-radius,y-radius,2*radius,2*radius);
- PSNewPath();
- PSArc(x,y, radius, 0,360);
- PSSetLineWidth(thickness);
- PSStroke();
- }
+ private void PSSetFont(int font, long size) {
+ size *= scale;
+ _s.append(fontName(font) + " findfont " + size + " scalefont setfont\n");
+ }
- public void fillCircle(long x,long y, long radius, long thickness,double graylevel)
- {
- x *= scale;
- y *= scale;
- radius *= scale;
- updateBoundingBox(x-radius,y-radius,2*radius,2*radius);
- PSNewPath();
- PSArc(x,y, radius, 0,360);
- PSSetLineWidth(thickness);
- PSSetGray(graylevel);
- PSFill();
- PSSetGray(0.0);
- }
+ public void setFont(int font, long size) {
+ PSSetFont(font, size);
+ }
- public void setScale(double sc)
- {
- scale = sc;
- }
-
- public String export()
- {
- return EPSHeader()+_s.toString()+EPSFooter();
- }
+ public void drawLine(long x0, long y0, long x1, long y1, long thickness) {
+ x0 *= scale;
+ y0 *= scale;
+ x1 *= scale;
+ y1 *= scale;
+ PSMoveTo(x0, y0);
+ PSLineTo(x1, y1);
+ PSSetLineWidth(thickness);
+ PSStroke();
+ }
- public void reset()
- {
- _s = new StringBuffer();
- minX = Long.MAX_VALUE;
- minY = Long.MAX_VALUE;
- maxX = Long.MIN_VALUE;
- maxY = Long.MIN_VALUE;
- scale = 1.0;
- }
+ public void drawText(long x, long y, String txt, long height) {
+ x *= scale;
+ y *= scale;
+ PSMoveTo(x, y);
+ _s.append("" + (height - 5) + " \n");
+ PSText(txt);
+ _s.append(" txtcenter\n");
+ }
+ public void drawRectangle(long x, long y, long w, long h, long thickness) {
+ x *= scale;
+ y *= scale;
+ w *= scale;
+ h *= scale;
+ updateBoundingBox(x, y, w, h);
+ PSNewPath();
+ PSMoveTo(x, y);
+ PSRLineTo(0, w);
+ PSRLineTo(h, 0);
+ PSRLineTo(0, -w);
+ PSRLineTo(-h, 0);
+ PSClosePath();
+ PSSetLineWidth(thickness);
+ PSStroke();
+ }
+
+ public void drawCircle(long x, long y, long radius, long thickness) {
+ x *= scale;
+ y *= scale;
+ radius *= scale;
+ updateBoundingBox(x - radius, y - radius, 2 * radius, 2 * radius);
+ PSNewPath();
+ PSArc(x, y, radius, 0, 360);
+ PSSetLineWidth(thickness);
+ PSStroke();
+ }
+
+ public void fillCircle(long x, long y, long radius, long thickness, double graylevel) {
+ x *= scale;
+ y *= scale;
+ radius *= scale;
+ updateBoundingBox(x - radius, y - radius, 2 * radius, 2 * radius);
+ PSNewPath();
+ PSArc(x, y, radius, 0, 360);
+ PSSetLineWidth(thickness);
+ PSSetGray(graylevel);
+ PSFill();
+ PSSetGray(0.0);
+ }
+
+ public void setScale(double sc) {
+ scale = sc;
+ }
+
+ public String export() {
+ return EPSHeader() + _s.toString() + EPSFooter();
+ }
+
+ public void reset() {
+ _s = new StringBuffer();
+ minX = Long.MAX_VALUE;
+ minY = Long.MAX_VALUE;
+ maxX = Long.MIN_VALUE;
+ maxY = Long.MIN_VALUE;
+ scale = 1.0;
+ }
+
+ public void setBoundingBox(long width, long height) {
+ }
}
diff -U 3 -H -d -r -N -- original_varna_2.0/varna/export/SVGExport.java src/varna/export/SVGExport.java
--- original_varna_2.0/varna/export/SVGExport.java 1970-01-01 01:00:00.000000000 +0100
+++ src/varna/export/SVGExport.java 2008-07-27 12:07:44.000000000 +0200
@@ -0,0 +1,264 @@
+package varna.export;
+
+import java.awt.Color;
+import java.awt.Rectangle;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import org.jdom.DocType;
+import org.jdom.Document;
+import org.jdom.Element;
+import org.jdom.Namespace;
+import org.jdom.output.Format;
+import org.jdom.output.XMLOutputter;
+
+public class SVGExport implements SecStrDrawingProducer {
+
+ private double _scale = 1.0;
+ private int _font = SecStrDrawingProducer.FONT_TIMES_ROMAN;
+ private long _fontsize = 10;
+ private Document document;
+ private Element elementSVG;
+ StringBuffer buf = new StringBuffer();
+ private String units = "";
+ private double scaleCoef = 1;
+ Rectangle rectBoundary = new Rectangle(0, 0, 0, 0);
+ Element targetElement;
+
+ public SVGExport() {
+ document = new Document();
+ elementSVG = new Element("svg");
+ elementSVG.setAttribute("version", "1.1");
+ elementSVG.setNamespace(Namespace.getNamespace("http://www.w3.org/2000/svg"));
+ Element title = new Element("title");
+ title.addContent("rna");
+ title.setNamespace(Namespace.getNamespace("http://www.w3.org/2000/svg"));
+ elementSVG.addContent(title);
+ document.addContent(elementSVG);
+ document.setDocType(new DocType("svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"));
+
+// targetElement = new Element("g");
+// targetElement.setNamespace(Namespace.getNamespace("http://www.w3.org/2000/svg"));
+ targetElement = elementSVG;
+// elementSVG.addContent(targetElement);
+ }
+
+ public void drawCircle(long x, long y, long radius, long thickness) {
+// x *= _scale;
+// y *= _scale;
+// radius *= _scale;
+// buf.append("1 3 0 " + thickness + " 0 7 50 -1 -1 0.000 1 0.0000 " + x + " " + y + " " + radius + " " + radius + " 1 1 1 1\n");
+
+ x *= _scale * scaleCoef;
+ y *= _scale * scaleCoef;
+ y = transformY(y);
+ radius *= _scale * scaleCoef;
+
+ Element e = new Element("circle");
+ e.setNamespace(Namespace.getNamespace("http://www.w3.org/2000/svg"));
+ e.setAttribute("cx", "" + x);
+ e.setAttribute("cy", "" + y);
+ e.setAttribute("r", "" + radius);
+ e.setAttribute("style", "stroke:rgb(99,99,99);stroke-width:" + thickness + ";");
+ e.setAttribute("fill", "none");
+// elementSVG.addContent(e);
+ }
+
+ public void drawLine(long x0, long y0, long x1, long y1, long thickness) {
+ x0 *= _scale * scaleCoef;
+ y0 *= _scale * scaleCoef;
+ x1 *= _scale * scaleCoef;
+ y1 *= _scale * scaleCoef;
+
+ y0 = transformY(y0);
+ y1 = transformY(y1);
+
+ Element e = new Element("line");
+ e.setNamespace(Namespace.getNamespace("http://www.w3.org/2000/svg"));
+ e.setAttribute("x1", "" + x0 + units);
+ e.setAttribute("y1", "" + y0 + units);
+ e.setAttribute("x2", "" + x1 + units);
+ e.setAttribute("y2", "" + y1 + units);
+// e.setAttribute("stroke-width", "" + thickness);
+ e.setAttribute("style", "stroke:rgb(99,99,99);stroke-width:" + thickness);
+ targetElement.addContent(e);
+// buf.append("2 1 0 " + thickness + " 0 7 60 -1 -1 0.000 0 0 -1 0 0 2\n" +
+// " " + x0 + " " + y0 + " " + x1 + " " + y1 + "\n");
+ }
+
+ public void drawLine(long x0, long y0, long x1, long y1, long thickness, Color strokeColor) {
+ String strokeColorStr = strokeColor.getRed() + "," + strokeColor.getGreen() + "," + strokeColor.getBlue();
+ x0 *= _scale * scaleCoef;
+ y0 *= _scale * scaleCoef;
+ x1 *= _scale * scaleCoef;
+ y1 *= _scale * scaleCoef;
+
+ y0 = transformY(y0);
+ y1 = transformY(y1);
+
+ Element e = new Element("line");
+ e.setNamespace(Namespace.getNamespace("http://www.w3.org/2000/svg"));
+ e.setAttribute("x1", "" + x0 + units);
+ e.setAttribute("y1", "" + y0 + units);
+ e.setAttribute("x2", "" + x1 + units);
+ e.setAttribute("y2", "" + y1 + units);
+// e.setAttribute("stroke-width", "" + thickness);
+ e.setAttribute("style", "stroke:rgb(" + strokeColorStr + ");stroke-width:" + thickness);
+ targetElement.addContent(e);
+// buf.append("2 1 0 " + thickness + " 0 7 60 -1 -1 0.000 0 0 -1 0 0 2\n" +
+// " " + x0 + " " + y0 + " " + x1 + " " + y1 + "\n");
+ }
+
+ public void drawRectangle(long x, long y, long w, long h, long thickness) {
+ x *= _scale * scaleCoef;
+ y *= _scale * scaleCoef;
+ h *= _scale * scaleCoef;
+ w *= _scale * scaleCoef;
+
+ y = transformY(y);
+
+ Element e = new Element("rect");
+ e.setNamespace(Namespace.getNamespace("http://www.w3.org/2000/svg"));
+ e.setAttribute("x", "" + x + units);
+ e.setAttribute("y", "" + y + units);
+ e.setAttribute("height", "" + h + units);
+ e.setAttribute("width", "" + w + units);
+ e.setAttribute("fill", "none");
+// e.setAttribute("stroke-width", "" + thickness);
+ e.setAttribute("style", "stroke:rgb(99,99,99);stroke-width:" + thickness);
+ targetElement.addContent(e);
+
+ // buf.append("2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5\n" +
+// "\t " + (x) + " " + (y) + " " + (x + w) + " " + (y) + " " + (x + w) + " " + (y + h) + " " + (x) + " " + (y + h) + " " + (x) + " " + (y) + "\n");
+ }
+
+ public void drawText(long x, long y, String txt, long height) {
+ x *= _scale * scaleCoef;
+ y *= _scale * scaleCoef;
+ height *= _scale * scaleCoef;
+
+ y = transformY(y);
+
+ long fontSize = height;
+ Element e = new Element("text");
+ e.setNamespace(Namespace.getNamespace("http://www.w3.org/2000/svg"));
+ e.setAttribute("x", "" + x);
+ e.setAttribute("y", "" + (y + height / 2 * 0.8));
+ e.setAttribute("font-size", "" + fontSize);
+ e.setAttribute("text-anchor", "middle");
+ e.addContent(txt);
+ targetElement.addContent(e);
+
+ // buf.append("4 1 0 40 -1 " + _font + " " + _fontsize + " 0.0000 6 " + height + " " + height + " " + x + " " + (y + height / 3) + " " + txt + "\\001\n");
+ }
+
+ public void drawText(long x, long y, String text, long height, Color textColor) {
+ String textColorStr = textColor.getRed() + "," + textColor.getGreen() + "," + textColor.getBlue();
+ x *= _scale * scaleCoef;
+ y *= _scale * scaleCoef;
+ height *= _scale * scaleCoef;
+
+ y = transformY(y);
+
+ long fontSize = height;
+ Element e = new Element("text");
+ e.setNamespace(Namespace.getNamespace("http://www.w3.org/2000/svg"));
+ e.setAttribute("x", "" + x);
+ e.setAttribute("y", "" + (y + height / 2 * 0.8));
+ e.setAttribute("font-size", "" + fontSize);
+ e.setAttribute("text-anchor", "middle");
+ e.setAttribute("style", "fill:rgb(" + textColorStr + ")");
+ e.addContent(text);
+ targetElement.addContent(e);
+
+ // buf.append("4 1 0 40 -1 " + _font + " " + _fontsize + " 0.0000 6 " + height + " " + height + " " + x + " " + (y + height / 3) + " " + txt + "\\001\n");
+ }
+
+ public void fillCircle(long x, long y, long radius, long thickness, double graylevel) {
+ int shade = (int) Math.round(graylevel * 20);
+ x *= _scale * scaleCoef;
+ y *= _scale * scaleCoef;
+ radius *= _scale * scaleCoef;
+ int fillColor = (int) (graylevel * 255);
+
+ y = transformY(y);
+
+ Element e = new Element("circle");
+ e.setNamespace(Namespace.getNamespace("http://www.w3.org/2000/svg"));
+ e.setAttribute("cx", "" + x);
+ e.setAttribute("cy", "" + y);
+ e.setAttribute("r", "" + radius);
+ e.setAttribute("style", "stroke:rgb(99,99,99);stroke-width:" + (thickness * 2) + ";fill:rgb(" + fillColor + "," + fillColor + "," + fillColor + ")");
+// e.setAttribute("stroke", "rgb(99,99,99)");
+// e.setAttribute("stroke-width", "" + thickness);
+// e.setAttribute("fill", "rgb(" + fillColor + "," + fillColor + "," + fillColor + ")");
+ targetElement.addContent(e);
+// buf.append("1 3 0 1 0 7 50 0 " + shade + " 0.000 1 0.0000 " + x + " " + y + " " + radius + " " + radius + " 1 1 1 1\n");
+ }
+
+
+ public void fillCircle(long x, long y, long radius, long thickness, Color strokeColor, Color fillColor ) {
+// x *= _scale;
+// y *= _scale;
+// radius *= _scale;
+// buf.append("1 3 0 " + thickness + " 0 7 50 -1 -1 0.000 1 0.0000 " + x + " " + y + " " + radius + " " + radius + " 1 1 1 1\n");
+ String strokeColorStr = strokeColor.getRed() + "," + strokeColor.getGreen() + "," + strokeColor.getBlue();
+ String fillColorStr = fillColor.getRed() + "," + fillColor.getGreen() + "," + fillColor.getBlue();
+
+ x *= _scale * scaleCoef;
+ y *= _scale * scaleCoef;
+ y = transformY(y);
+ radius *= _scale * scaleCoef;
+
+ Element e = new Element("circle");
+ e.setNamespace(Namespace.getNamespace("http://www.w3.org/2000/svg"));
+ e.setAttribute("cx", "" + x);
+ e.setAttribute("cy", "" + y);
+ e.setAttribute("r", "" + radius);
+ e.setAttribute("style", "stroke:rgb(" + strokeColorStr + ");stroke-width:" + (thickness * 2) + ";fill:rgb(" + fillColorStr + ")");
+// e.setAttribute("style", "stroke:rgb(99,99,99);stroke-width:" + thickness + ";");
+ e.setAttribute("fill", "none");
+ targetElement.addContent(e);
+// elementSVG.addContent(e);
+ }
+
+
+ public String export() {
+ StringBuffer sb = new StringBuffer(256);
+ StringWriter sw = new StringWriter();
+
+// targetElement.setAttribute("transform", "matrix(1,0,0,-1,0," + (rectBoundary.getHeight() * _scale * scaleCoef) + ")");
+// targetElement.setAttribute("transform", "matrix(1,0,0,1,0,0)");
+
+ XMLOutputter op = new XMLOutputter(Format.getPrettyFormat());
+ try {
+ op.output(document, sw);
+ } catch (IOException ex) {
+ Logger.getLogger(SVGExport.class.getName()).log(Level.SEVERE, null, ex);
+ }
+
+ return sw.toString();
+ }
+
+ public void reset() {
+ buf = new StringBuffer();
+ }
+
+ public void setFont(int font, long size) {
+ _font = font;
+ _fontsize = size;
+ }
+
+ public void setScale(double sc) {
+ _scale = sc;
+ }
+
+ public void setBoundingBox(long width, long height) {
+ rectBoundary = new Rectangle(0, 0, (int) width, (int) height);
+ }
+
+ private long transformY(long y) {
+ return (long) (((rectBoundary.getHeight() + 45 ) * _scale * scaleCoef ) - y );
+ }
+}
diff -U 3 -H -d -r -N -- original_varna_2.0/varna/export/SecStrDrawingProducer.java src/varna/export/SecStrDrawingProducer.java
--- original_varna_2.0/varna/export/SecStrDrawingProducer.java 2008-01-12 01:12:00.000000000 +0100
+++ src/varna/export/SecStrDrawingProducer.java 2008-07-27 11:05:42.000000000 +0200
@@ -1,25 +1,37 @@
package varna.export;
public interface SecStrDrawingProducer {
- public static final int FONT_TIMES_ROMAN = 0;
- public static final int FONT_TIMES_BOLD = 1;
- public static final int FONT_TIMES_ITALIC = 2;
- public static final int FONT_TIMES_BOLD_ITALIC = 3;
- public static final int FONT_HELVETICA = 16;
- public static final int FONT_HELVETICA_OBLIQUE = 17;
- public static final int FONT_HELVETICA_BOLD = 18;
- public static final int FONT_HELVETICA_BOLD_OBLIQUE = 19;
- public static final int FONT_COURIER = 12;
- public static final int FONT_COURIER_BOLD = 13;
- public static final int FONT_COURIER_OBLIQUE = 14;
- public static final int FONT_COURIER_BOLD_OBLIQUE = 15;
- public void drawLine(long x0, long y0, long x1, long y1, long thickness);
- public void drawText(long x, long y, String txt, long height);
- public void drawRectangle(long x,long y, long w, long h, long thickness);
- public void drawCircle(long x,long y, long radius, long thickness);
- public void fillCircle(long x,long y, long radius, long thickness,double graylevel);
- public void setScale(double sc);
- public void setFont(int font,long size);
- public String export();
- public void reset();
+
+ public static final int FONT_TIMES_ROMAN = 0;
+ public static final int FONT_TIMES_BOLD = 1;
+ public static final int FONT_TIMES_ITALIC = 2;
+ public static final int FONT_TIMES_BOLD_ITALIC = 3;
+ public static final int FONT_HELVETICA = 16;
+ public static final int FONT_HELVETICA_OBLIQUE = 17;
+ public static final int FONT_HELVETICA_BOLD = 18;
+ public static final int FONT_HELVETICA_BOLD_OBLIQUE = 19;
+ public static final int FONT_COURIER = 12;
+ public static final int FONT_COURIER_BOLD = 13;
+ public static final int FONT_COURIER_OBLIQUE = 14;
+ public static final int FONT_COURIER_BOLD_OBLIQUE = 15;
+
+ public void drawLine(long x0, long y0, long x1, long y1, long thickness);
+
+ public void drawText(long x, long y, String txt, long height);
+
+ public void drawRectangle(long x, long y, long w, long h, long thickness);
+
+ public void drawCircle(long x, long y, long radius, long thickness);
+
+ public void fillCircle(long x, long y, long radius, long thickness, double graylevel);
+
+ public void setBoundingBox(long width, long height);
+
+ public void setScale(double sc);
+
+ public void setFont(int font, long size);
+
+ public String export();
+
+ public void reset();
}
diff -U 3 -H -d -r -N -- original_varna_2.0/varna/export/XFIGExport.java src/varna/export/XFIGExport.java
--- original_varna_2.0/varna/export/XFIGExport.java 2008-01-12 01:15:00.000000000 +0100
+++ src/varna/export/XFIGExport.java 2008-05-13 23:55:47.000000000 +0200
@@ -2,85 +2,83 @@
public class XFIGExport implements SecStrDrawingProducer {
- private double _scale=1.0;
- private int _font = SecStrDrawingProducer.FONT_TIMES_ROMAN;
- private long _fontsize = 10;
-
- private String XFIGHeader()
- {
- return
- "#FIG 3.2\n"+
- "Landscape\n"+
- "Center\n"+
- "Inches\n"+
- "Letter \n"+
- "100.00\n"+
- "Single\n"+
- "-2\n"+
- "1200 2\n";
- }
-
- StringBuffer buf = new StringBuffer();
-
- public void drawCircle(long x, long y, long radius, long thickness) {
- x *= _scale;
- y *= _scale;
- radius *= _scale;
- buf.append("1 3 0 "+thickness+" 0 7 50 -1 -1 0.000 1 0.0000 "+x+" "+y+" "+radius+" "+radius+" 1 1 1 1\n");
- }
+ private double _scale = 1.0;
+ private int _font = SecStrDrawingProducer.FONT_TIMES_ROMAN;
+ private long _fontsize = 10;
- public void drawLine(long x0, long y0, long x1, long y1, long thickness) {
- x0 *= _scale;
- y0 *= _scale;
- x1 *= _scale;
- y1 *= _scale;
-
- buf.append("2 1 0 "+thickness+" 0 7 60 -1 -1 0.000 0 0 -1 0 0 2\n"+
- " "+x0+" "+y0+" "+x1+" "+y1+"\n");
- }
+ private String XFIGHeader() {
+ return "#FIG 3.2\n" +
+ "Landscape\n" +
+ "Center\n" +
+ "Inches\n" +
+ "Letter \n" +
+ "100.00\n" +
+ "Single\n" +
+ "-2\n" +
+ "1200 2\n";
+ }
+ StringBuffer buf = new StringBuffer();
- public void drawRectangle(long x, long y, long w, long h, long thickness) {
- x *= _scale;
- y *= _scale;
- h *= _scale;
- w *= _scale;
- buf.append("2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5\n"+
- "\t "+(x)+" "+(y)+" "+(x+w)+" "+(y)+" "+(x+w)+" "+(y+h)+" "+(x)+" "+(y+h)+" "+(x)+" "+(y)+"\n");
- }
+ public void drawCircle(long x, long y, long radius, long thickness) {
+ x *= _scale;
+ y *= _scale;
+ radius *= _scale;
+ buf.append("1 3 0 " + thickness + " 0 7 50 -1 -1 0.000 1 0.0000 " + x + " " + y + " " + radius + " " + radius + " 1 1 1 1\n");
+ }
- public void drawText(long x, long y, String txt, long height) {
- x *= _scale;
- y *= _scale;
- height *= _scale;
- buf.append("4 1 0 40 -1 "+_font+" "+_fontsize+" 0.0000 6 "+height+" "+height+" "+x+" "+(y+height/3)+" "+txt+"\\001\n");
- }
+ public void drawLine(long x0, long y0, long x1, long y1, long thickness) {
+ x0 *= _scale;
+ y0 *= _scale;
+ x1 *= _scale;
+ y1 *= _scale;
- public void fillCircle(long x, long y, long radius, long thickness, double graylevel)
- {
- int shade = (int)Math.round(graylevel*20);
- x *= _scale;
- y *= _scale;
- radius *= _scale;
- buf.append("1 3 0 1 0 7 50 0 "+shade+" 0.000 1 0.0000 "+x+" "+y+" "+radius+" "+radius+" 1 1 1 1\n");
- }
+ buf.append("2 1 0 " + thickness + " 0 7 60 -1 -1 0.000 0 0 -1 0 0 2\n" +
+ " " + x0 + " " + y0 + " " + x1 + " " + y1 + "\n");
+ }
- public String export() {
- // TODO Auto-generated method stub
- return XFIGHeader()+buf;
- }
+ public void drawRectangle(long x, long y, long w, long h, long thickness) {
+ x *= _scale;
+ y *= _scale;
+ h *= _scale;
+ w *= _scale;
+ buf.append("2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5\n" +
+ "\t " + (x) + " " + (y) + " " + (x + w) + " " + (y) + " " + (x + w) + " " + (y + h) + " " + (x) + " " + (y + h) + " " + (x) + " " + (y) + "\n");
+ }
+ public void drawText(long x, long y, String txt, long height) {
+ x *= _scale;
+ y *= _scale;
+ height *= _scale;
+ buf.append("4 1 0 40 -1 " + _font + " " + _fontsize + " 0.0000 6 " + height + " " + height + " " + x + " " + (y + height / 3) + " " + txt + "\\001\n");
+ }
- public void reset() {
- buf = new StringBuffer();
- }
+ public void fillCircle(long x, long y, long radius, long thickness, double graylevel) {
+ int shade = (int) Math.round(graylevel * 20);
+ x *= _scale;
+ y *= _scale;
+ radius *= _scale;
+ buf.append("1 3 0 1 0 7 50 0 " + shade + " 0.000 1 0.0000 " + x + " " + y + " " + radius + " " + radius + " 1 1 1 1\n");
+ }
- public void setFont(int font, long size) {
- _font = font;
- _fontsize = size;
- }
+ public String export() {
+ // TODO Auto-generated method stub
+ return XFIGHeader() + buf;
+ }
- public void setScale(double sc) {
- _scale = sc;
- }
+ public void reset() {
+ buf = new StringBuffer();
+ }
+ public void setFont(int font, long size) {
+ _font = font;
+ _fontsize = size;
+ }
+
+ public void setScale(double sc) {
+ _scale = sc;
+ }
+
+ public void setBoundingBox(long width, long height) {
+ }
+
}