389efd1b88c85bbf145396613400286c3a8750bf
[jalview.git] / src / jalview / gui / AppVarnaBinding.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3  * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
10  * 
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.gui;
19
20 import java.awt.BorderLayout;
21 import java.awt.Color;
22 import java.awt.Component;
23 import java.awt.Dimension;
24 import java.awt.Font;
25 import java.awt.GridLayout;
26 import java.awt.datatransfer.DataFlavor;
27 import java.awt.datatransfer.Transferable;
28 import java.awt.dnd.DnDConstants;
29 import java.awt.dnd.DropTarget;
30 import java.awt.dnd.DropTargetDragEvent;
31 import java.awt.dnd.DropTargetDropEvent;
32 import java.awt.dnd.DropTargetEvent;
33 import java.awt.dnd.DropTargetListener;
34 import java.awt.event.ActionEvent;
35 import java.awt.event.ActionListener;
36 import java.awt.event.MouseEvent;
37 import java.awt.event.MouseListener;
38 import java.io.File;
39 import java.text.DateFormat;
40 import java.util.ArrayList;
41 import java.util.Date;
42 import java.util.List;
43
44 import javax.swing.DefaultListModel;
45 import javax.swing.DefaultListSelectionModel;
46 import javax.swing.Icon;
47 import javax.swing.JButton;
48 import javax.swing.JFrame;
49 import javax.swing.JLabel;
50 import javax.swing.JList;
51 import javax.swing.JOptionPane;
52 import javax.swing.JPanel;
53 import javax.swing.JScrollPane;
54 import javax.swing.JSplitPane;
55 import javax.swing.JTextField;
56 import javax.swing.ListModel;
57 import javax.swing.ListSelectionModel;
58 import javax.swing.UIManager;
59 import javax.swing.UnsupportedLookAndFeelException;
60 import javax.swing.event.ListSelectionEvent;
61 import javax.swing.event.ListSelectionListener;
62
63 import fr.orsay.lri.varna.VARNAPanel;
64 import fr.orsay.lri.varna.components.ReorderableJList;
65 import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
66 import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
67 import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
68 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
69 import fr.orsay.lri.varna.interfaces.InterfaceVARNAListener;
70 import fr.orsay.lri.varna.models.FullBackup;
71 import fr.orsay.lri.varna.models.VARNAConfig;
72 import fr.orsay.lri.varna.models.rna.Mapping;
73 import fr.orsay.lri.varna.models.rna.RNA;
74
75 public class AppVarnaBinding extends JFrame implements DropTargetListener, InterfaceVARNAListener, MouseListener {
76
77         /**
78          * 
79          */
80         //private static final long serialVersionUID = -790155708306987257L;
81
82         private String DEFAULT_SEQUENCE = "CAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIA";
83
84         private String DEFAULT_STRUCTURE1 = "..(((((...(((((...(((((...(((((.....)))))...))))).....(((((...(((((.....)))))...))))).....)))))...)))))..";
85         private String DEFAULT_STRUCTURE2 = "..(((((...(((((...(((((........(((((...(((((.....)))))...)))))..................))))).....)))))...)))))..";
86         // private static final String DEFAULT_STRUCTURE1 = "((((....))))";
87         // private static final String DEFAULT_STRUCTURE2 =
88         // "((((..(((....)))..))))";
89
90         public VARNAPanel vp;
91
92         private JPanel _tools = new JPanel();
93         private JPanel _input = new JPanel();
94
95         private JPanel _seqPanel = new JPanel();
96         private JPanel _strPanel = new JPanel();
97         private JLabel _info = new JLabel();
98         private JTextField _str = new JTextField();
99         private JTextField _seq = new JTextField();
100         private JLabel _strLabel = new JLabel(" Str:");
101         private JLabel _seqLabel = new JLabel(" Seq:");
102         private JButton _createButton = new JButton("Create");
103         private JButton _deleteButton = new JButton("Delete");
104         private JButton _duplicateButton = new JButton("Snapshot");
105         
106         private JPanel _listPanel = new JPanel();
107         private ReorderableJList _sideList = null;
108
109
110         private static String errorOpt = "error";
111         @SuppressWarnings("unused")
112         private boolean _error;
113
114         private Color _backgroundColor = Color.white;
115
116         private static int _nextID = 1;
117         @SuppressWarnings("unused")
118         private int _algoCode;
119         
120         private BackupHolder _rnaList;
121
122
123         public AppVarnaBinding() {
124                 super("VARNA in Jalview");
125                 //this.set_seq("ATGC");
126                 //this.set_str(".().");
127                 //RNAPanelDemoInit();
128                 
129                 //initVarna("ATGCATGATATATATATAT","....((((...))))....");
130                 initVarna(this.DEFAULT_SEQUENCE,this.DEFAULT_STRUCTURE1);
131         }
132         
133         public AppVarnaBinding(String seq){
134                 super("VARNA in Jalview");
135                 initVarna(seq,this.DEFAULT_STRUCTURE1);
136         }
137         
138         
139         
140         private void initVarna(String seq, String str){
141                 DefaultListModel dlm = new DefaultListModel(); 
142             
143
144                 DefaultListSelectionModel m = new DefaultListSelectionModel();
145             m.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
146             m.setLeadAnchorNotificationEnabled(false);
147             
148             
149                 _sideList = new ReorderableJList();
150                 _sideList.setModel(dlm);
151                 _sideList.addMouseListener(this);
152             _sideList.setSelectionModel(m);
153             _sideList.setPreferredSize(new Dimension(100, 0));
154             _sideList.addListSelectionListener( new ListSelectionListener(){
155                         public void valueChanged(ListSelectionEvent arg0) {
156                                 if (!_sideList.isSelectionEmpty() && !arg0.getValueIsAdjusting())
157                                 {
158                                         FullBackup  sel = (FullBackup) _sideList.getSelectedValue();
159                                         Mapping map = Mapping.DefaultOutermostMapping(vp.getRNA().getSize(), sel.rna.getSize());
160                                         vp.showRNAInterpolated(sel.rna,sel.config,map);
161                                         _seq.setText(sel.rna.getSeq());
162                                         _str.setText(sel.rna.getStructDBN());
163                                 }
164                         }
165             });
166
167             _rnaList = new BackupHolder(dlm,_sideList);
168                 RNA _RNA1 = new RNA("User defined 1");
169                 
170                 try {
171                         vp = new VARNAPanel("0",".");
172                         _RNA1.setRNA(seq, str);
173                         _RNA1.drawRNARadiate(vp.getConfig());
174                 } catch (ExceptionNonEqualLength e) {
175                         vp.errorDialog(e);
176                 } catch (ExceptionUnmatchedClosingParentheses e2) {
177                 e2.printStackTrace();
178                 } catch (ExceptionFileFormatOrSyntax e3) {
179                 e3.printStackTrace();
180                 }
181                 vp.setPreferredSize(new Dimension(400, 400));
182                 _rnaList.add(vp.getConfig().clone(),_RNA1,generateDefaultName(),true);
183
184                 setBackground(_backgroundColor);
185                 vp.setBackground(_backgroundColor);
186
187                 getContentPane().setLayout(new BorderLayout());
188                 getContentPane().add(vp, BorderLayout.CENTER);
189
190                 setVisible(true);
191                 vp.addVARNAListener(this);
192         }
193
194         private void RNAPanelDemoInit() 
195         {
196             DefaultListModel dlm = new DefaultListModel(); 
197             
198
199                 int marginTools = 40;
200
201             DefaultListSelectionModel m = new DefaultListSelectionModel();
202             m.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
203             m.setLeadAnchorNotificationEnabled(false);
204             
205             
206                 _sideList = new ReorderableJList();
207                 _sideList.setModel(dlm);
208                 _sideList.addMouseListener(this);
209             _sideList.setSelectionModel(m);
210             _sideList.setPreferredSize(new Dimension(100, 0));
211             _sideList.addListSelectionListener( new ListSelectionListener(){
212                         public void valueChanged(ListSelectionEvent arg0) {
213                                 //System.out.println(arg0);
214                                 if (!_sideList.isSelectionEmpty() && !arg0.getValueIsAdjusting())
215                                 {
216                                         FullBackup  sel = (FullBackup) _sideList.getSelectedValue();
217                                         Mapping map = Mapping.DefaultOutermostMapping(vp.getRNA().getSize(), sel.rna.getSize());
218                                         vp.showRNAInterpolated(sel.rna,sel.config,map);
219                                         _seq.setText(sel.rna.getSeq());
220                                         _str.setText(sel.rna.getStructDBN());
221                                 }
222                         }
223             });
224
225             _rnaList = new BackupHolder(dlm,_sideList);
226                 RNA _RNA1 = new RNA("User defined 1");
227                 RNA _RNA2 = new RNA("User defined 2");
228                 try {
229                         vp = new VARNAPanel("0",".");
230                         _RNA1.setRNA(DEFAULT_SEQUENCE, DEFAULT_STRUCTURE1);
231                         _RNA1.drawRNARadiate(vp.getConfig());
232                         _RNA2.setRNA(DEFAULT_SEQUENCE, DEFAULT_STRUCTURE2);
233                         _RNA2.drawRNARadiate(vp.getConfig());
234                 } catch (ExceptionNonEqualLength e) {
235                         vp.errorDialog(e);
236                 } catch (ExceptionUnmatchedClosingParentheses e2) {
237                 e2.printStackTrace();
238                 } catch (ExceptionFileFormatOrSyntax e3) {
239                 e3.printStackTrace();
240                 }
241                 vp.setPreferredSize(new Dimension(400, 400));
242             _rnaList.add(vp.getConfig().clone(),_RNA2,generateDefaultName());
243             _rnaList.add(vp.getConfig().clone(),_RNA1,generateDefaultName(),true);
244
245             JScrollPane listScroller = new JScrollPane(_sideList);
246             listScroller.setPreferredSize(new Dimension(150, 0));
247
248                 setBackground(_backgroundColor);
249                 vp.setBackground(_backgroundColor);
250
251
252                 Font textFieldsFont = Font.decode("MonoSpaced-PLAIN-12");
253
254                 _seqLabel.setHorizontalTextPosition(JLabel.LEFT);
255                 _seqLabel.setPreferredSize(new Dimension(marginTools, 15));
256                 _seq.setFont(textFieldsFont);
257                 _seq.setText(DEFAULT_SEQUENCE);
258
259                 _createButton.addActionListener(new ActionListener() {
260                         public void actionPerformed(ActionEvent e) {
261                                 try {
262                                 RNA nRNA = new RNA(generateDefaultName());
263                                 nRNA.setRNA(_seq.getText(), _str.getText());
264                                 nRNA.drawRNARadiate(vp.getConfig());
265                                 _rnaList.add(new VARNAConfig(),nRNA,true);
266                                 } catch (ExceptionUnmatchedClosingParentheses e1) {
267                                         JOptionPane.showMessageDialog(vp, e1.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
268                                 } catch (ExceptionFileFormatOrSyntax e1) {
269                                         JOptionPane.showMessageDialog(vp, e1.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
270                                 }
271                         }
272                 });
273
274
275                 _seqPanel.setLayout(new BorderLayout());
276                 _seqPanel.add(_seqLabel, BorderLayout.WEST);
277                 _seqPanel.add(_seq, BorderLayout.CENTER);
278
279                 _strLabel.setPreferredSize(new Dimension(marginTools, 15));
280                 _strLabel.setHorizontalTextPosition(JLabel.LEFT);
281                 _str.setFont(textFieldsFont);
282                 _strPanel.setLayout(new BorderLayout());
283                 _strPanel.add(_strLabel, BorderLayout.WEST);
284                 _strPanel.add(_str, BorderLayout.CENTER);
285
286                 _input.setLayout(new GridLayout(2, 0));
287                 _input.add(_seqPanel);
288                 _input.add(_strPanel);
289
290                 JPanel goPanel = new JPanel();
291                 goPanel.setLayout(new BorderLayout());
292
293                 _tools.setLayout(new BorderLayout());
294                 _tools.add(_input, BorderLayout.CENTER);
295                 _tools.add(_info, BorderLayout.SOUTH);
296                 _tools.add(goPanel, BorderLayout.EAST);
297
298                 _deleteButton.addActionListener(new ActionListener() {
299                         public void actionPerformed(ActionEvent e) {
300                                 _rnaList.removeSelected();
301                         }
302                 });
303                 _duplicateButton.addActionListener(new ActionListener() {
304                         public void actionPerformed(ActionEvent e) {
305                                         _rnaList.add((VARNAConfig)vp.getConfig().clone(),vp.getRNA().clone(),vp.getRNA().getName()+"-"+DateFormat.getTimeInstance(DateFormat.LONG).format(new Date()),true); 
306                         }});
307                 
308                 JPanel ops = new JPanel();
309                 ops.setLayout(new GridLayout(1,2));
310                 ops.add(_deleteButton);
311                 ops.add(_duplicateButton);
312
313                 JLabel j = new JLabel("Structures Manager",JLabel.CENTER);
314                 _listPanel.setLayout(new BorderLayout());
315                 
316                 _listPanel.add(ops,BorderLayout.SOUTH);
317                 _listPanel.add(j,BorderLayout.NORTH);
318                 _listPanel.add(listScroller,BorderLayout.CENTER);
319
320                 goPanel.add(_createButton, BorderLayout.CENTER);
321
322                 JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,_listPanel,vp);
323                 getContentPane().setLayout(new BorderLayout());
324                 getContentPane().add(split, BorderLayout.CENTER);
325                 getContentPane().add(_tools, BorderLayout.NORTH);
326
327                 setVisible(true);
328                 DropTarget dt = new DropTarget(vp, this);
329                 
330                 vp.addVARNAListener(this);
331         }
332         
333         public static String generateDefaultName()
334         {
335                 return "User file #"+_nextID++;
336         }
337
338         public RNA getRNA() {
339                 return (RNA)_sideList.getSelectedValue();
340         }
341
342
343
344         public String[][] getParameterInfo() {
345                 String[][] info = {
346                                 // Parameter Name Kind of Value Description,
347                                 { "sequenceDBN", "String", "A raw RNA sequence" },
348                                 { "structureDBN", "String",
349                                                 "An RNA structure in dot bracket notation (DBN)" },
350                                 { errorOpt, "boolean", "To show errors" }, };
351                 return info;
352         }
353
354         public void init() {
355                 vp.setBackground(_backgroundColor);
356                 _error = true;
357         }
358
359         @SuppressWarnings("unused")
360         private Color getSafeColor(String col, Color def) {
361                 Color result;
362                 try {
363                         result = Color.decode(col);
364                 } catch (Exception e) {
365                         try {
366                                 result = Color.getColor(col, def);
367                         } catch (Exception e2) {
368                                 return def;
369                         }
370                 }
371                 return result;
372         }
373
374         public VARNAPanel get_varnaPanel() {
375                 return vp;
376         }
377
378         public void set_varnaPanel(VARNAPanel surface) {
379                 vp = surface;
380         }
381
382
383         public String get_seq() {
384                 return _seq.getText();
385         }
386
387         public void set_seq(String _seq) {
388                 this._seq.setText(_seq);
389         }
390         
391         public String get_str(){
392                 return _str.getText();
393         }
394         
395         public void set_str(String _str){
396                 this._str.setText(_str);
397         }
398
399         public JLabel get_info() {
400                 return _info;
401         }
402
403         public void set_info(JLabel _info) {
404                 this._info = _info;
405         }
406
407         public static void main(String[] args) {
408                 AppVarnaBinding d = new AppVarnaBinding();
409                 d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
410                 d.pack();
411                 d.setVisible(true);
412         }
413         
414
415         public void dragEnter(DropTargetDragEvent arg0) {
416                 // TODO Auto-generated method stub
417                 
418         }
419
420         public void dragExit(DropTargetEvent arg0) {
421                 // TODO Auto-generated method stub
422                 
423         }
424
425         public void dragOver(DropTargetDragEvent arg0) {
426                 // TODO Auto-generated method stub
427                 
428         }
429
430         public void drop(DropTargetDropEvent dtde) {
431             try {
432                 Transferable tr = dtde.getTransferable();
433                 DataFlavor[] flavors = tr.getTransferDataFlavors();
434                 for (int i = 0; i < flavors.length; i++) {
435             if (flavors[i].isFlavorJavaFileListType()) {
436               dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
437               Object ob = tr.getTransferData(flavors[i]);
438               if (ob instanceof List)
439               {
440                   List list = (List) ob;
441                   for (int j = 0; j < list.size(); j++) {
442                   Object o = list.get(j);
443                   
444                   if (dtde.getSource() instanceof DropTarget)
445                   {
446                           DropTarget dt = (DropTarget) dtde.getSource();
447                           Component c = dt.getComponent();
448                           if (c instanceof VARNAPanel)
449                           {
450                                           String path = o.toString();
451                                   VARNAPanel vp = (VARNAPanel) c;
452                                           try{
453                                   FullBackup bck =  VARNAPanel.importSession(path);
454                                   _rnaList.add(bck.config, bck.rna,bck.name,true);
455                                           }
456                                           catch (ExceptionLoadingFailed e3)
457                                           {
458                                                   RNA r = new RNA();
459                                                   r.loadSecStr(path);
460                                                   r.drawRNA(vp.getConfig());
461                                                   String name =r.getName();
462                                                   if (name.equals(""))
463                                                   { 
464                                                           name = path.substring(path.lastIndexOf(File.separatorChar)+1);
465                                                   }
466                                                   _rnaList.add(vp.getConfig().clone(),r,name,true);
467                                           }                                       
468                           }
469                   }
470                   }
471               }
472               // If we made it this far, everything worked.
473               dtde.dropComplete(true);
474               return;
475             }
476                 }
477                 // Hmm, the user must not have dropped a file list
478                 dtde.rejectDrop();
479               } catch (Exception e) {
480                 e.printStackTrace();
481                 dtde.rejectDrop();
482               }
483                 
484         }
485
486         public void dropActionChanged(DropTargetDragEvent arg0) {
487         }
488
489         private class BackupHolder{
490                 private DefaultListModel _rnaList;
491                 private ArrayList<RNA> _rnas = new ArrayList<RNA>();
492                 JList _l;
493                 
494                 public BackupHolder(DefaultListModel rnaList, JList l)
495                 {
496                         _rnaList = rnaList;
497                         _l = l;
498                 }
499                 
500                 public void add(VARNAConfig c, RNA r)
501                 {
502                         add(c, r, r.getName(),false);
503                 }
504
505                 public void add(VARNAConfig c, RNA r,boolean select)
506                 {
507                         add(c, r, r.getName(),select);
508                 }
509
510                 public void add(VARNAConfig c, RNA r, String name)
511                 {
512                         add(c, r, name,false);                  
513                 }
514                 public void add(VARNAConfig c, RNA r, String name, boolean select)
515                 {
516                         if (select){
517                                 _l.removeSelectionInterval(0, _rnaList.size());
518                         }
519                         if (name.equals(""))
520                         {
521                                 name = generateDefaultName();
522                         }
523                         FullBackup bck = new FullBackup(c,r,name);
524                         _rnas.add(0, r);
525                         _rnaList.add(0,bck);
526                         if (select){
527                           _l.setSelectedIndex(0);
528                         }
529                 }
530
531                 public void remove(int i)
532                 {
533                         _rnas.remove(i);
534                         _rnaList.remove(i);
535                         
536                 }
537                 public DefaultListModel getModel()
538                 {
539                         return _rnaList;
540                 }
541                 public boolean contains(RNA r)
542                 {
543                         return _rnas.contains(r);
544                 }
545                 /*public int getSize()
546                 {
547                         return _rnaList.getSize();
548                 }*/
549                 public FullBackup getElementAt(int i)
550                 {
551                         return (FullBackup) _rnaList.getElementAt(i);
552                 }
553                 
554                 public void removeSelected()
555                 {
556                         int i = _l.getSelectedIndex();
557                         if (i!=-1)
558                         {
559                           if (_rnaList.getSize()==1)
560                           {
561                                   RNA r = new RNA();
562                                   try {
563                                         r.setRNA(" ", ".");
564                                   } catch (ExceptionUnmatchedClosingParentheses e1) {
565                                   } catch (ExceptionFileFormatOrSyntax e1) {
566                                   }
567                                   vp.showRNA(r);
568                                   vp.repaint();
569                           }
570                           else
571                           {  
572                                  int newi = i+1;
573                                  if (newi==_rnaList.getSize())
574                                  {
575                                          newi = _rnaList.getSize()-2;
576                                  }
577                                  FullBackup bck = (FullBackup) _rnaList.getElementAt(newi);
578                                  _l.setSelectedValue(bck,true);
579                           }
580                           _rnaList.remove(i);
581                         }
582
583                 }
584         }
585
586         public void onLayoutChanged() {
587                 // TODO Auto-generated method stub
588                 
589         }
590
591         public void onUINewStructure(VARNAConfig v, RNA r) {
592                 _rnaList.add(v, r,"",true);
593         }
594
595         public void onWarningEmitted(String s) {
596                 // TODO Auto-generated method stub
597                 
598         }
599
600         public void mouseClicked(MouseEvent e) {
601                            if(e.getClickCount() == 2){
602                              int index = _sideList.locationToIndex(e.getPoint());
603                              ListModel dlm = _sideList.getModel();
604                              FullBackup item = (FullBackup) dlm.getElementAt(index);;
605                              _sideList.ensureIndexIsVisible(index);
606                              Object newName = JOptionPane.showInputDialog(
607                                             this,
608                                             "Specify a new name for this RNA",
609                                             "Rename RNA", 
610                                             JOptionPane.QUESTION_MESSAGE,
611                                             (Icon)null,
612                                             null,
613                                             item.toString());
614                              if (newName!=null)
615                              {
616                                  item.name = newName.toString();
617                                  this._sideList.repaint();
618                              }
619                              }
620         }
621
622         public void mouseEntered(MouseEvent arg0) {
623                 // TODO Auto-generated method stub
624                 
625         }
626
627         public void mouseExited(MouseEvent arg0) {
628                 // TODO Auto-generated method stub
629                 
630         }
631
632         public void mousePressed(MouseEvent arg0) {
633                 // TODO Auto-generated method stub
634                 
635         }
636
637         public void mouseReleased(MouseEvent arg0) {
638                 // TODO Auto-generated method stub
639                 
640         }
641 }
642
643
644 /*
645         public static void main(String[] args)
646         {
647                 JTextField str = new JTextField("ATGC");
648                 
649                 AppVarnaBinding vab = new AppVarnaBinding();
650                 vab.varnagui.set_seq(str);
651                 vab.varnagui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
652                 vab.varnagui.pack();
653                 vab.varnagui.setVisible(true);  
654         }
655 }
656 */