JAL-842, AppVarnaBinding was filled with a minimalistic method to
[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         private 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         
134         
135         private void initVarna(String seq, String str){
136                 DefaultListModel dlm = new DefaultListModel(); 
137             
138
139                 DefaultListSelectionModel m = new DefaultListSelectionModel();
140             m.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
141             m.setLeadAnchorNotificationEnabled(false);
142             
143             
144                 _sideList = new ReorderableJList();
145                 _sideList.setModel(dlm);
146                 _sideList.addMouseListener(this);
147             _sideList.setSelectionModel(m);
148             _sideList.setPreferredSize(new Dimension(100, 0));
149             _sideList.addListSelectionListener( new ListSelectionListener(){
150                         public void valueChanged(ListSelectionEvent arg0) {
151                                 if (!_sideList.isSelectionEmpty() && !arg0.getValueIsAdjusting())
152                                 {
153                                         FullBackup  sel = (FullBackup) _sideList.getSelectedValue();
154                                         Mapping map = Mapping.DefaultOutermostMapping(_vp.getRNA().getSize(), sel.rna.getSize());
155                                         _vp.showRNAInterpolated(sel.rna,sel.config,map);
156                                         _seq.setText(sel.rna.getSeq());
157                                         _str.setText(sel.rna.getStructDBN());
158                                 }
159                         }
160             });
161
162             _rnaList = new BackupHolder(dlm,_sideList);
163                 RNA _RNA1 = new RNA("User defined 1");
164                 
165                 try {
166                         _vp = new VARNAPanel("0",".");
167                         _RNA1.setRNA(seq, str);
168                         _RNA1.drawRNARadiate(_vp.getConfig());
169                 } catch (ExceptionNonEqualLength e) {
170                         _vp.errorDialog(e);
171                 } catch (ExceptionUnmatchedClosingParentheses e2) {
172                 e2.printStackTrace();
173                 } catch (ExceptionFileFormatOrSyntax e3) {
174                 e3.printStackTrace();
175                 }
176                 _vp.setPreferredSize(new Dimension(400, 400));
177                 _rnaList.add(_vp.getConfig().clone(),_RNA1,generateDefaultName(),true);
178
179                 setBackground(_backgroundColor);
180                 _vp.setBackground(_backgroundColor);
181
182                 getContentPane().setLayout(new BorderLayout());
183                 getContentPane().add(_vp, BorderLayout.CENTER);
184
185                 setVisible(true);
186                 _vp.addVARNAListener(this);
187         }
188
189         private void RNAPanelDemoInit() 
190         {
191             DefaultListModel dlm = new DefaultListModel(); 
192             
193
194                 int marginTools = 40;
195
196             DefaultListSelectionModel m = new DefaultListSelectionModel();
197             m.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
198             m.setLeadAnchorNotificationEnabled(false);
199             
200             
201                 _sideList = new ReorderableJList();
202                 _sideList.setModel(dlm);
203                 _sideList.addMouseListener(this);
204             _sideList.setSelectionModel(m);
205             _sideList.setPreferredSize(new Dimension(100, 0));
206             _sideList.addListSelectionListener( new ListSelectionListener(){
207                         public void valueChanged(ListSelectionEvent arg0) {
208                                 //System.out.println(arg0);
209                                 if (!_sideList.isSelectionEmpty() && !arg0.getValueIsAdjusting())
210                                 {
211                                         FullBackup  sel = (FullBackup) _sideList.getSelectedValue();
212                                         Mapping map = Mapping.DefaultOutermostMapping(_vp.getRNA().getSize(), sel.rna.getSize());
213                                         _vp.showRNAInterpolated(sel.rna,sel.config,map);
214                                         _seq.setText(sel.rna.getSeq());
215                                         _str.setText(sel.rna.getStructDBN());
216                                 }
217                         }
218             });
219
220             _rnaList = new BackupHolder(dlm,_sideList);
221                 RNA _RNA1 = new RNA("User defined 1");
222                 RNA _RNA2 = new RNA("User defined 2");
223                 try {
224                         _vp = new VARNAPanel("0",".");
225                         _RNA1.setRNA(DEFAULT_SEQUENCE, DEFAULT_STRUCTURE1);
226                         _RNA1.drawRNARadiate(_vp.getConfig());
227                         _RNA2.setRNA(DEFAULT_SEQUENCE, DEFAULT_STRUCTURE2);
228                         _RNA2.drawRNARadiate(_vp.getConfig());
229                 } catch (ExceptionNonEqualLength e) {
230                         _vp.errorDialog(e);
231                 } catch (ExceptionUnmatchedClosingParentheses e2) {
232                 e2.printStackTrace();
233                 } catch (ExceptionFileFormatOrSyntax e3) {
234                 e3.printStackTrace();
235                 }
236                 _vp.setPreferredSize(new Dimension(400, 400));
237             _rnaList.add(_vp.getConfig().clone(),_RNA2,generateDefaultName());
238             _rnaList.add(_vp.getConfig().clone(),_RNA1,generateDefaultName(),true);
239
240             JScrollPane listScroller = new JScrollPane(_sideList);
241             listScroller.setPreferredSize(new Dimension(150, 0));
242
243                 setBackground(_backgroundColor);
244                 _vp.setBackground(_backgroundColor);
245
246
247                 Font textFieldsFont = Font.decode("MonoSpaced-PLAIN-12");
248
249                 _seqLabel.setHorizontalTextPosition(JLabel.LEFT);
250                 _seqLabel.setPreferredSize(new Dimension(marginTools, 15));
251                 _seq.setFont(textFieldsFont);
252                 _seq.setText(DEFAULT_SEQUENCE);
253
254                 _createButton.addActionListener(new ActionListener() {
255                         public void actionPerformed(ActionEvent e) {
256                                 try {
257                                 RNA nRNA = new RNA(generateDefaultName());
258                                 nRNA.setRNA(_seq.getText(), _str.getText());
259                                 nRNA.drawRNARadiate(_vp.getConfig());
260                                 _rnaList.add(new VARNAConfig(),nRNA,true);
261                                 } catch (ExceptionUnmatchedClosingParentheses e1) {
262                                         JOptionPane.showMessageDialog(_vp, e1.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
263                                 } catch (ExceptionFileFormatOrSyntax e1) {
264                                         JOptionPane.showMessageDialog(_vp, e1.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
265                                 }
266                         }
267                 });
268
269
270                 _seqPanel.setLayout(new BorderLayout());
271                 _seqPanel.add(_seqLabel, BorderLayout.WEST);
272                 _seqPanel.add(_seq, BorderLayout.CENTER);
273
274                 _strLabel.setPreferredSize(new Dimension(marginTools, 15));
275                 _strLabel.setHorizontalTextPosition(JLabel.LEFT);
276                 _str.setFont(textFieldsFont);
277                 _strPanel.setLayout(new BorderLayout());
278                 _strPanel.add(_strLabel, BorderLayout.WEST);
279                 _strPanel.add(_str, BorderLayout.CENTER);
280
281                 _input.setLayout(new GridLayout(2, 0));
282                 _input.add(_seqPanel);
283                 _input.add(_strPanel);
284
285                 JPanel goPanel = new JPanel();
286                 goPanel.setLayout(new BorderLayout());
287
288                 _tools.setLayout(new BorderLayout());
289                 _tools.add(_input, BorderLayout.CENTER);
290                 _tools.add(_info, BorderLayout.SOUTH);
291                 _tools.add(goPanel, BorderLayout.EAST);
292
293                 _deleteButton.addActionListener(new ActionListener() {
294                         public void actionPerformed(ActionEvent e) {
295                                 _rnaList.removeSelected();
296                         }
297                 });
298                 _duplicateButton.addActionListener(new ActionListener() {
299                         public void actionPerformed(ActionEvent e) {
300                                         _rnaList.add((VARNAConfig)_vp.getConfig().clone(),_vp.getRNA().clone(),_vp.getRNA().getName()+"-"+DateFormat.getTimeInstance(DateFormat.LONG).format(new Date()),true); 
301                         }});
302                 
303                 JPanel ops = new JPanel();
304                 ops.setLayout(new GridLayout(1,2));
305                 ops.add(_deleteButton);
306                 ops.add(_duplicateButton);
307
308                 JLabel j = new JLabel("Structures Manager",JLabel.CENTER);
309                 _listPanel.setLayout(new BorderLayout());
310                 
311                 _listPanel.add(ops,BorderLayout.SOUTH);
312                 _listPanel.add(j,BorderLayout.NORTH);
313                 _listPanel.add(listScroller,BorderLayout.CENTER);
314
315                 goPanel.add(_createButton, BorderLayout.CENTER);
316
317                 JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,_listPanel,_vp);
318                 getContentPane().setLayout(new BorderLayout());
319                 getContentPane().add(split, BorderLayout.CENTER);
320                 getContentPane().add(_tools, BorderLayout.NORTH);
321
322                 setVisible(true);
323                 DropTarget dt = new DropTarget(_vp, this);
324                 
325                 _vp.addVARNAListener(this);
326         }
327         
328         public static String generateDefaultName()
329         {
330                 return "User file #"+_nextID++;
331         }
332
333         public RNA getRNA() {
334                 return (RNA)_sideList.getSelectedValue();
335         }
336
337
338
339         public String[][] getParameterInfo() {
340                 String[][] info = {
341                                 // Parameter Name Kind of Value Description,
342                                 { "sequenceDBN", "String", "A raw RNA sequence" },
343                                 { "structureDBN", "String",
344                                                 "An RNA structure in dot bracket notation (DBN)" },
345                                 { errorOpt, "boolean", "To show errors" }, };
346                 return info;
347         }
348
349         public void init() {
350                 _vp.setBackground(_backgroundColor);
351                 _error = true;
352         }
353
354         @SuppressWarnings("unused")
355         private Color getSafeColor(String col, Color def) {
356                 Color result;
357                 try {
358                         result = Color.decode(col);
359                 } catch (Exception e) {
360                         try {
361                                 result = Color.getColor(col, def);
362                         } catch (Exception e2) {
363                                 return def;
364                         }
365                 }
366                 return result;
367         }
368
369         public VARNAPanel get_varnaPanel() {
370                 return _vp;
371         }
372
373         public void set_varnaPanel(VARNAPanel surface) {
374                 _vp = surface;
375         }
376
377
378         public String get_seq() {
379                 return _seq.getText();
380         }
381
382         public void set_seq(String _seq) {
383                 this._seq.setText(_seq);
384         }
385         
386         public String get_str(){
387                 return _str.getText();
388         }
389         
390         public void set_str(String _str){
391                 this._str.setText(_str);
392         }
393
394         public JLabel get_info() {
395                 return _info;
396         }
397
398         public void set_info(JLabel _info) {
399                 this._info = _info;
400         }
401
402         public static void main(String[] args) {
403                 AppVarnaBinding d = new AppVarnaBinding();
404                 d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
405                 d.pack();
406                 d.setVisible(true);
407         }
408         
409
410         public void dragEnter(DropTargetDragEvent arg0) {
411                 // TODO Auto-generated method stub
412                 
413         }
414
415         public void dragExit(DropTargetEvent arg0) {
416                 // TODO Auto-generated method stub
417                 
418         }
419
420         public void dragOver(DropTargetDragEvent arg0) {
421                 // TODO Auto-generated method stub
422                 
423         }
424
425         public void drop(DropTargetDropEvent dtde) {
426             try {
427                 Transferable tr = dtde.getTransferable();
428                 DataFlavor[] flavors = tr.getTransferDataFlavors();
429                 for (int i = 0; i < flavors.length; i++) {
430             if (flavors[i].isFlavorJavaFileListType()) {
431               dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
432               Object ob = tr.getTransferData(flavors[i]);
433               if (ob instanceof List)
434               {
435                   List list = (List) ob;
436                   for (int j = 0; j < list.size(); j++) {
437                   Object o = list.get(j);
438                   
439                   if (dtde.getSource() instanceof DropTarget)
440                   {
441                           DropTarget dt = (DropTarget) dtde.getSource();
442                           Component c = dt.getComponent();
443                           if (c instanceof VARNAPanel)
444                           {
445                                           String path = o.toString();
446                                   VARNAPanel vp = (VARNAPanel) c;
447                                           try{
448                                   FullBackup bck =  VARNAPanel.importSession(path);
449                                   _rnaList.add(bck.config, bck.rna,bck.name,true);
450                                           }
451                                           catch (ExceptionLoadingFailed e3)
452                                           {
453                                                   RNA r = new RNA();
454                                                   r.loadSecStr(path);
455                                                   r.drawRNA(vp.getConfig());
456                                                   String name =r.getName();
457                                                   if (name.equals(""))
458                                                   { 
459                                                           name = path.substring(path.lastIndexOf(File.separatorChar)+1);
460                                                   }
461                                                   _rnaList.add(vp.getConfig().clone(),r,name,true);
462                                           }                                       
463                           }
464                   }
465                   }
466               }
467               // If we made it this far, everything worked.
468               dtde.dropComplete(true);
469               return;
470             }
471                 }
472                 // Hmm, the user must not have dropped a file list
473                 dtde.rejectDrop();
474               } catch (Exception e) {
475                 e.printStackTrace();
476                 dtde.rejectDrop();
477               }
478                 
479         }
480
481         public void dropActionChanged(DropTargetDragEvent arg0) {
482         }
483
484         private class BackupHolder{
485                 private DefaultListModel _rnaList;
486                 private ArrayList<RNA> _rnas = new ArrayList<RNA>();
487                 JList _l;
488                 
489                 public BackupHolder(DefaultListModel rnaList, JList l)
490                 {
491                         _rnaList = rnaList;
492                         _l = l;
493                 }
494                 
495                 public void add(VARNAConfig c, RNA r)
496                 {
497                         add(c, r, r.getName(),false);
498                 }
499
500                 public void add(VARNAConfig c, RNA r,boolean select)
501                 {
502                         add(c, r, r.getName(),select);
503                 }
504
505                 public void add(VARNAConfig c, RNA r, String name)
506                 {
507                         add(c, r, name,false);                  
508                 }
509                 public void add(VARNAConfig c, RNA r, String name, boolean select)
510                 {
511                         if (select){
512                                 _l.removeSelectionInterval(0, _rnaList.size());
513                         }
514                         if (name.equals(""))
515                         {
516                                 name = generateDefaultName();
517                         }
518                         FullBackup bck = new FullBackup(c,r,name);
519                         _rnas.add(0, r);
520                         _rnaList.add(0,bck);
521                         if (select){
522                           _l.setSelectedIndex(0);
523                         }
524                 }
525
526                 public void remove(int i)
527                 {
528                         _rnas.remove(i);
529                         _rnaList.remove(i);
530                         
531                 }
532                 public DefaultListModel getModel()
533                 {
534                         return _rnaList;
535                 }
536                 public boolean contains(RNA r)
537                 {
538                         return _rnas.contains(r);
539                 }
540                 /*public int getSize()
541                 {
542                         return _rnaList.getSize();
543                 }*/
544                 public FullBackup getElementAt(int i)
545                 {
546                         return (FullBackup) _rnaList.getElementAt(i);
547                 }
548                 
549                 public void removeSelected()
550                 {
551                         int i = _l.getSelectedIndex();
552                         if (i!=-1)
553                         {
554                           if (_rnaList.getSize()==1)
555                           {
556                                   RNA r = new RNA();
557                                   try {
558                                         r.setRNA(" ", ".");
559                                   } catch (ExceptionUnmatchedClosingParentheses e1) {
560                                   } catch (ExceptionFileFormatOrSyntax e1) {
561                                   }
562                                   _vp.showRNA(r);
563                                   _vp.repaint();
564                           }
565                           else
566                           {  
567                                  int newi = i+1;
568                                  if (newi==_rnaList.getSize())
569                                  {
570                                          newi = _rnaList.getSize()-2;
571                                  }
572                                  FullBackup bck = (FullBackup) _rnaList.getElementAt(newi);
573                                  _l.setSelectedValue(bck,true);
574                           }
575                           _rnaList.remove(i);
576                         }
577
578                 }
579         }
580
581         public void onLayoutChanged() {
582                 // TODO Auto-generated method stub
583                 
584         }
585
586         public void onUINewStructure(VARNAConfig v, RNA r) {
587                 _rnaList.add(v, r,"",true);
588         }
589
590         public void onWarningEmitted(String s) {
591                 // TODO Auto-generated method stub
592                 
593         }
594
595         public void mouseClicked(MouseEvent e) {
596                            if(e.getClickCount() == 2){
597                              int index = _sideList.locationToIndex(e.getPoint());
598                              ListModel dlm = _sideList.getModel();
599                              FullBackup item = (FullBackup) dlm.getElementAt(index);;
600                              _sideList.ensureIndexIsVisible(index);
601                              Object newName = JOptionPane.showInputDialog(
602                                             this,
603                                             "Specify a new name for this RNA",
604                                             "Rename RNA", 
605                                             JOptionPane.QUESTION_MESSAGE,
606                                             (Icon)null,
607                                             null,
608                                             item.toString());
609                              if (newName!=null)
610                              {
611                                  item.name = newName.toString();
612                                  this._sideList.repaint();
613                              }
614                              }
615         }
616
617         public void mouseEntered(MouseEvent arg0) {
618                 // TODO Auto-generated method stub
619                 
620         }
621
622         public void mouseExited(MouseEvent arg0) {
623                 // TODO Auto-generated method stub
624                 
625         }
626
627         public void mousePressed(MouseEvent arg0) {
628                 // TODO Auto-generated method stub
629                 
630         }
631
632         public void mouseReleased(MouseEvent arg0) {
633                 // TODO Auto-generated method stub
634                 
635         }
636 }
637
638
639 /*
640         public static void main(String[] args)
641         {
642                 JTextField str = new JTextField("ATGC");
643                 
644                 AppVarnaBinding vab = new AppVarnaBinding();
645                 vab.varnagui.set_seq(str);
646                 vab.varnagui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
647                 vab.varnagui.pack();
648                 vab.varnagui.setVisible(true);  
649         }
650 }
651 */