0e00de4f9d5ab2df833089a1a7456531e59f9bc7
[jalview.git] / src / jalview / gui / AppJmol.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 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.util.*;
21 import java.awt.*;
22 import javax.swing.*;
23 import javax.swing.event.*;
24
25 import java.awt.event.*;
26 import java.io.*;
27
28 import jalview.jbgui.GStructureViewer;
29 import jalview.api.AlignmentViewPanel;
30 import jalview.api.SequenceStructureBinding;
31 import jalview.bin.Cache;
32 import jalview.datamodel.*;
33 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
34 import jalview.structure.*;
35 import jalview.datamodel.PDBEntry;
36 import jalview.io.*;
37 import jalview.schemes.*;
38
39 public class AppJmol extends GStructureViewer implements Runnable,
40         SequenceStructureBinding, ViewSetProvider
41
42 {
43   AppJmolBinding jmb;
44
45   JPanel scriptWindow;
46
47   JSplitPane splitPane;
48
49   RenderPanel renderPanel;
50
51   AlignmentPanel ap;
52
53   Vector atomsPicked = new Vector();
54
55   private boolean addingStructures = false;
56
57   /**
58    * 
59    * @param file
60    * @param id
61    * @param seq
62    * @param ap
63    * @param loadStatus
64    * @param bounds
65    * @deprecated defaults to AppJmol(String[] files, ... , viewid);
66    */
67   public AppJmol(String file, String id, SequenceI[] seq,
68           AlignmentPanel ap, String loadStatus, Rectangle bounds)
69   {
70     this(file, id, seq, ap, loadStatus, bounds, null);
71   }
72
73   /**
74    * @deprecated
75    */
76   public AppJmol(String file, String id, SequenceI[] seq,
77           AlignmentPanel ap, String loadStatus, Rectangle bounds,
78           String viewid)
79   {
80     this(new String[]
81     { file }, new String[]
82     { id }, new SequenceI[][]
83     { seq }, ap, true, true, false, loadStatus, bounds, viewid);
84   }
85
86   ViewSelectionMenu seqColourBy;
87
88   /**
89    * 
90    * @param files
91    * @param ids
92    * @param seqs
93    * @param ap
94    * @param usetoColour
95    *          - add the alignment panel to the list used for colouring these
96    *          structures
97    * @param useToAlign
98    *          - add the alignment panel to the list used for aligning these
99    *          structures
100    * @param leaveColouringToJmol
101    *          - do not update the colours from any other source. Jmol is handling them
102    * @param loadStatus
103    * @param bounds
104    * @param viewid
105    */
106   public AppJmol(String[] files, String[] ids, SequenceI[][] seqs,
107           AlignmentPanel ap, boolean usetoColour, boolean useToAlign, boolean leaveColouringToJmol,
108           String loadStatus, Rectangle bounds, String viewid)
109   {
110     PDBEntry[] pdbentrys = new PDBEntry[files.length];
111     for (int i = 0; i < pdbentrys.length; i++)
112     {
113       PDBEntry pdbentry = new PDBEntry();
114       pdbentry.setFile(files[i]);
115       pdbentry.setId(ids[i]);
116       pdbentrys[i] = pdbentry;
117     }
118     // / TODO: check if protocol is needed to be set, and if chains are
119     // autodiscovered.
120     jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(), pdbentrys, seqs, null, null);
121
122     jmb.setLoadingFromArchive(true);
123     addAlignmentPanel(ap);
124     if (useToAlign)
125     {
126       useAlignmentPanelForSuperposition(ap);
127     }
128     if (leaveColouringToJmol || !usetoColour)
129     {
130       jmb.setColourBySequence(false);
131       seqColour.setSelected(false);
132       jmolColour.setSelected(true);
133     }
134     if (usetoColour)
135     {
136       useAlignmentPanelForColourbyseq(ap);
137       jmb.setColourBySequence(true);
138       seqColour.setSelected(true);
139       jmolColour.setSelected(false);
140     }
141     this.setBounds(bounds);
142     initMenus();
143     viewId = viewid;
144     // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
145     // bounds.width,bounds.height);
146
147     this.addInternalFrameListener(new InternalFrameAdapter()
148     {
149       public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
150       {
151         closeViewer();
152       }
153     });
154     initJmol(loadStatus); // pdbentry, seq, JBPCHECK!
155
156   }
157
158   private void initMenus()
159   {
160     seqColour.setSelected(jmb.isColourBySequence());
161     jmolColour.setSelected(!jmb.isColourBySequence());
162     if (_colourwith==null)
163     {
164       _colourwith=new Vector<AlignmentPanel>();
165     }
166     if (_alignwith==null)
167     {
168       _alignwith=new Vector<AlignmentPanel>();
169     }
170     
171     seqColourBy = new ViewSelectionMenu("Colour by ..", this, _colourwith,
172             new ItemListener()
173             {
174
175               @Override
176               public void itemStateChanged(ItemEvent e)
177               {
178                 if (!seqColour.isSelected())
179                 {
180                   seqColour.doClick();
181                 }
182                 else
183                 {
184                   // update the jmol display now.
185                   seqColour_actionPerformed(null);
186                 }
187               }
188             });
189     viewMenu.add(seqColourBy);
190     final ItemListener handler;
191     JMenu alpanels = new ViewSelectionMenu("Superpose with ..", this,
192             _alignwith, handler = new ItemListener()
193             {
194
195               @Override
196               public void itemStateChanged(ItemEvent e)
197               {
198                 alignStructs.setEnabled(_alignwith.size() > 0);
199                 alignStructs.setToolTipText("Align structures using "
200                         + _alignwith.size() + " linked alignment views");
201               }
202             });
203     handler.itemStateChanged(null);
204     jmolActionMenu.add(alpanels);
205     jmolActionMenu.addMenuListener(new MenuListener()
206     {
207
208       @Override
209       public void menuSelected(MenuEvent e)
210       {
211         handler.itemStateChanged(null);
212       }
213
214       @Override
215       public void menuDeselected(MenuEvent e)
216       {
217         // TODO Auto-generated method stub
218
219       }
220
221       @Override
222       public void menuCanceled(MenuEvent e)
223       {
224         // TODO Auto-generated method stub
225
226       }
227     });
228   }
229   IProgressIndicator progressBar = null;
230
231   /**
232    * add a single PDB structure to a new or existing Jmol view
233    * @param pdbentry
234    * @param seq
235    * @param chains
236    * @param ap
237    */
238   public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
239           final AlignmentPanel ap)
240   {
241     progressBar = ap.alignFrame;
242     // ////////////////////////////////
243     // Is the pdb file already loaded?
244     String alreadyMapped = ap.getStructureSelectionManager().alreadyMappedToFile(
245                     pdbentry.getId());
246
247     if (alreadyMapped != null)
248     {
249       int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
250               pdbentry.getId() + " is already displayed."
251                       + "\nDo you want to re-use this viewer ?",
252               "Map Sequences to Visible Window: " + pdbentry.getId(),
253               JOptionPane.YES_NO_OPTION);
254
255       if (option == JOptionPane.YES_OPTION)
256       {
257         // TODO : Fix multiple seq to one chain issue here.
258         ap.getStructureSelectionManager().setMapping(seq, chains, alreadyMapped,
259                         AppletFormatAdapter.FILE);
260         if (ap.seqPanel.seqCanvas.fr != null)
261         {
262           ap.seqPanel.seqCanvas.fr.featuresAdded();
263           ap.paintAlignment(true);
264         }
265
266         // Now this AppJmol is mapped to new sequences. We must add them to
267         // the exisiting array
268         JInternalFrame[] frames = Desktop.instance.getAllFrames();
269
270         for (int i = 0; i < frames.length; i++)
271         {
272           if (frames[i] instanceof AppJmol)
273           {
274             final AppJmol topJmol = ((AppJmol) frames[i]);
275             // JBPNOTE: this looks like a binding routine, rather than a gui
276             // routine
277             for (int pe = 0; pe < topJmol.jmb.pdbentry.length; pe++)
278             {
279               if (topJmol.jmb.pdbentry[pe].getFile().equals(alreadyMapped))
280               {
281                 topJmol.jmb.addSequence(pe, seq);
282                 topJmol.addAlignmentPanel(ap);
283                 // add it to the set used for colouring
284                 topJmol.useAlignmentPanelForColourbyseq(ap);
285                 topJmol.buildJmolActionMenu();
286                 ap.getStructureSelectionManager().sequenceColoursChanged(ap);
287                 break;
288               }
289             }
290           }
291         }
292
293         return;
294       }
295     }
296     // /////////////////////////////////
297     // Check if there are other Jmol views involving this alignment
298     // and prompt user about adding this molecule to one of them
299     Vector existingViews = getJmolsFor(ap);
300     if (existingViews.size() > 0)
301     {
302       Enumeration jm = existingViews.elements();
303       while (jm.hasMoreElements())
304       {
305         AppJmol topJmol = (AppJmol) jm.nextElement();
306         // TODO: highlight topJmol in view somehow
307         int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
308                 "Do you want to add " + pdbentry.getId()
309                         + " to the view called\n'" + topJmol.getTitle()
310                         + "'\n", "Align to existing structure view",
311                 JOptionPane.YES_NO_OPTION);
312         if (option == JOptionPane.YES_OPTION)
313         {
314           topJmol.useAlignmentPanelForSuperposition(ap);
315           topJmol.addStructure(pdbentry, seq, chains, true, ap.alignFrame);
316           return;
317         }
318       }
319     }
320     // /////////////////////////////////
321     openNewJmol(ap, new PDBEntry[] { pdbentry }, new SequenceI[][] { seq });
322   }
323   private void openNewJmol(AlignmentPanel ap, PDBEntry[] pdbentrys, SequenceI[][] seqs) {
324     progressBar = ap.alignFrame;
325     jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(), pdbentrys, seqs, null, null);
326     addAlignmentPanel(ap);
327     useAlignmentPanelForColourbyseq(ap);
328     if (pdbentrys.length>1)
329     {
330       alignAddedStructures=true;
331       useAlignmentPanelForSuperposition(ap);
332     }
333     jmb.setColourBySequence(true);
334     setSize(400, 400); // probably should be a configurable/dynamic default here
335     initMenus();
336     worker=null;
337       {
338         addingStructures = false;
339         worker = new Thread(this);
340         worker.start();
341       }
342     this.addInternalFrameListener(new InternalFrameAdapter()
343     {
344       public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
345       {
346         closeViewer();
347       }
348     });
349
350   }
351
352   /**
353    * create a new Jmol containing several structures superimposed using the given alignPanel.
354    * @param ap
355    * @param pe
356    * @param seqs
357    */
358   public AppJmol(AlignmentPanel ap, PDBEntry[] pe, SequenceI[][] seqs)
359   {
360     openNewJmol(ap, pe, seqs);
361   }
362
363   /**
364    * list of sequenceSet ids associated with the view
365    */
366   ArrayList<String> _aps = new ArrayList();
367
368   public AlignmentPanel[] getAllAlignmentPanels()
369   {
370     AlignmentPanel[] t, list = new AlignmentPanel[0];
371     for (String setid : _aps)
372     {
373       AlignmentPanel[] panels = PaintRefresher.getAssociatedPanels(setid);
374       if (panels != null)
375       {
376         t = new AlignmentPanel[list.length + panels.length];
377         System.arraycopy(list, 0, t, 0, list.length);
378         System.arraycopy(panels, 0, t, list.length, panels.length);
379         list = t;
380       }
381     }
382
383     return list;
384   }
385
386   /**
387    * list of alignment panels to use for superposition
388    */
389   Vector<AlignmentPanel> _alignwith = new Vector<AlignmentPanel>();
390
391   /**
392    * list of alignment panels that are used for colouring structures by aligned
393    * sequences
394    */
395   Vector<AlignmentPanel> _colourwith = new Vector<AlignmentPanel>();
396
397   /**
398    * set the primary alignmentPanel reference and add another alignPanel to the
399    * list of ones to use for colouring and aligning
400    * 
401    * @param nap
402    */
403   public void addAlignmentPanel(AlignmentPanel nap)
404   {
405     if (ap == null)
406     {
407       ap = nap;
408     }
409     if (!_aps.contains(nap.av.getSequenceSetId()))
410     {
411       _aps.add(nap.av.getSequenceSetId());
412     }
413   }
414
415   /**
416    * remove any references held to the given alignment panel
417    * 
418    * @param nap
419    */
420   public void removeAlignmentPanel(AlignmentPanel nap)
421   {
422     try
423     {
424       _alignwith.remove(nap);
425       _colourwith.remove(nap);
426       if (ap == nap)
427       {
428         ap = null;
429         for (AlignmentPanel aps : getAllAlignmentPanels())
430         {
431           if (aps != nap)
432           {
433             ap = aps;
434             break;
435           }
436         }
437       }
438     } catch (Exception ex)
439     {
440     }
441     if (ap != null)
442     {
443       buildJmolActionMenu();
444     }
445   }
446
447   public void useAlignmentPanelForSuperposition(AlignmentPanel nap)
448   {
449     addAlignmentPanel(nap);
450     if (!_alignwith.contains(nap))
451     {
452       _alignwith.add(nap);
453     }
454   }
455
456   public void excludeAlignmentPanelForSuperposition(AlignmentPanel nap)
457   {
458     if (_alignwith.contains(nap))
459     {
460       _alignwith.remove(nap);
461     }
462   }
463
464   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap, boolean enableColourBySeq)
465   {
466     useAlignmentPanelForColourbyseq(nap);
467     jmb.setColourBySequence(enableColourBySeq);
468     seqColour.setSelected(enableColourBySeq);
469     jmolColour.setSelected(!enableColourBySeq);
470   }
471   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap)
472   {
473     addAlignmentPanel(nap);
474     if (!_colourwith.contains(nap))
475     {
476       _colourwith.add(nap);
477     }
478   }
479
480   public void excludeAlignmentPanelForColourbyseq(AlignmentPanel nap)
481   {
482     if (_colourwith.contains(nap))
483     {
484       _colourwith.remove(nap);
485     }
486   }
487
488   /**
489    * pdb retrieval thread.
490    */
491   private Thread worker = null;
492
493   /**
494    * add a new structure (with associated sequences and chains) to this viewer,
495    * retrieving it if necessary first.
496    * 
497    * @param pdbentry
498    * @param seq
499    * @param chains
500    * @param alignFrame
501    * @param align
502    *          if true, new structure(s) will be align using associated alignment
503    */
504   private void addStructure(final PDBEntry pdbentry, final SequenceI[] seq,
505           final String[] chains, final boolean b,
506           final IProgressIndicator alignFrame)
507   {
508     if (pdbentry.getFile() == null)
509     {
510       if (worker != null && worker.isAlive())
511       {
512         // a retrieval is in progress, wait around and add ourselves to the
513         // queue.
514         new Thread(new Runnable()
515         {
516           public void run()
517           {
518             while (worker != null && worker.isAlive() && _started)
519             {
520               try
521               {
522                 Thread.sleep(100 + ((int) Math.random() * 100));
523
524               } catch (Exception e)
525               {
526               }
527
528             }
529             // and call ourselves again.
530             addStructure(pdbentry, seq, chains, b, alignFrame);
531           }
532         }).start();
533         return;
534       }
535     }
536     // otherwise, start adding the structure.
537     jmb.addSequenceAndChain(new PDBEntry[]
538     { pdbentry }, new SequenceI[][]
539     { seq }, new String[][]
540     { chains });
541     addingStructures = true;
542     _started = false;
543     alignAddedStructures = b;
544     progressBar = alignFrame; // visual indication happens on caller frame.
545     (worker = new Thread(this)).start();
546     return;
547   }
548
549   private Vector getJmolsFor(AlignmentPanel ap2)
550   {
551     Vector otherJmols = new Vector();
552     // Now this AppJmol is mapped to new sequences. We must add them to
553     // the exisiting array
554     JInternalFrame[] frames = Desktop.instance.getAllFrames();
555
556     for (int i = 0; i < frames.length; i++)
557     {
558       if (frames[i] instanceof AppJmol)
559       {
560         AppJmol topJmol = ((AppJmol) frames[i]);
561         if (topJmol.isLinkedWith(ap2))
562         {
563           otherJmols.addElement(topJmol);
564         }
565       }
566     }
567     return otherJmols;
568   }
569
570   void initJmol(String command)
571   {
572     jmb.setFinishedInit(false);
573     renderPanel = new RenderPanel();
574     // TODO: consider waiting until the structure/view is fully loaded before
575     // displaying
576     this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
577     jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
578             getBounds().width, getBounds().height);
579     if (scriptWindow == null)
580     {
581       BorderLayout bl = new BorderLayout();
582       bl.setHgap(0);
583       bl.setVgap(0);
584       scriptWindow = new JPanel(bl);
585       scriptWindow.setVisible(false);
586     }
587     ;
588     jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
589             null);
590     jmb.newJmolPopup(true, "Jmol", true);
591     if (command==null)
592     {
593       command="";
594     }
595     jmb.evalStateCommand(command);
596     jmb.setFinishedInit(true);
597   }
598
599   void setChainMenuItems(Vector chains)
600   {
601     chainMenu.removeAll();
602     if (chains == null)
603     {
604       return;
605     }
606     JMenuItem menuItem = new JMenuItem("All");
607     menuItem.addActionListener(new ActionListener()
608     {
609       public void actionPerformed(ActionEvent evt)
610       {
611         allChainsSelected = true;
612         for (int i = 0; i < chainMenu.getItemCount(); i++)
613         {
614           if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
615             ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
616         }
617         centerViewer();
618         allChainsSelected = false;
619       }
620     });
621
622     chainMenu.add(menuItem);
623
624     for (int c = 0; c < chains.size(); c++)
625     {
626       menuItem = new JCheckBoxMenuItem(chains.elementAt(c).toString(), true);
627       menuItem.addItemListener(new ItemListener()
628       {
629         public void itemStateChanged(ItemEvent evt)
630         {
631           if (!allChainsSelected)
632             centerViewer();
633         }
634       });
635
636       chainMenu.add(menuItem);
637     }
638   }
639
640   boolean allChainsSelected = false;
641
642   private boolean alignAddedStructures = false;
643
644   void centerViewer()
645   {
646     Vector toshow = new Vector();
647     String lbl;
648     int mlength, p, mnum;
649     for (int i = 0; i < chainMenu.getItemCount(); i++)
650     {
651       if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
652       {
653         JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
654         if (item.isSelected())
655         {
656           toshow.addElement(item.getText());
657         }
658       }
659     }
660     jmb.centerViewer(toshow);
661   }
662
663   void closeViewer()
664   {
665     jmb.closeViewer();
666     ap = null;
667     _aps.clear();
668     _alignwith.clear();
669     _colourwith.clear();
670     // TODO: check for memory leaks where instance isn't finalised because jmb
671     // holds a reference to the window
672     jmb = null;
673   }
674
675   /**
676    * state flag for PDB retrieval thread
677    */
678   private boolean _started = false;
679
680   public void run()
681   {
682     _started = true;
683     String pdbid = "";
684     // todo - record which pdbids were successfuly imported.
685     StringBuffer errormsgs = new StringBuffer(), files = new StringBuffer();
686     try
687     {
688       String[] curfiles = jmb.getPdbFile(); // files currently in viewer
689       // TODO: replace with reference fetching/transfer code (validate PDBentry
690       // as a DBRef?)
691       jalview.ws.dbsources.Pdb pdbclient = new jalview.ws.dbsources.Pdb();
692       for (int pi = 0; pi < jmb.pdbentry.length; pi++)
693       {
694         String file = jmb.pdbentry[pi].getFile();
695         if (file == null)
696         {
697           // retrieve the pdb and store it locally
698           AlignmentI pdbseq = null;
699           pdbid = jmb.pdbentry[pi].getId();
700           long hdl = pdbid.hashCode() - System.currentTimeMillis();
701           if (progressBar != null)
702           {
703             progressBar.setProgressBar("Fetching PDB " + pdbid, hdl);
704           }
705           try
706           {
707             pdbseq = pdbclient.getSequenceRecords(pdbid = jmb.pdbentry[pi]
708                     .getId());
709           } catch (OutOfMemoryError oomerror)
710           {
711             new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
712           } catch (Exception ex)
713           {
714             ex.printStackTrace();
715             errormsgs.append("'" + pdbid + "'");
716           }
717           if (progressBar != null)
718           {
719             progressBar.setProgressBar("Finished.", hdl);
720           }
721           if (pdbseq != null)
722           {
723             // just transfer the file name from the first sequence's first
724             // PDBEntry
725             jmb.pdbentry[pi].setFile(file = ((PDBEntry) pdbseq
726                     .getSequenceAt(0).getPDBId().elementAt(0)).getFile());
727             files.append(" \"" + file + "\"");
728           }
729           else
730           {
731             errormsgs.append("'" + pdbid + "' ");
732           }
733         }
734         else
735         {
736           if (curfiles != null && curfiles.length > 0)
737           {
738             addingStructures = true; // already files loaded.
739             for (int c = 0; c < curfiles.length; c++)
740             {
741               if (curfiles[c].equals(file))
742               {
743                 file = null;
744                 break;
745               }
746             }
747           }
748           if (file != null)
749           {
750             files.append(" \"" + file + "\"");
751           }
752         }
753       }
754     } catch (OutOfMemoryError oomerror)
755     {
756       new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
757     } catch (Exception ex)
758     {
759       ex.printStackTrace();
760       errormsgs.append("When retrieving pdbfiles : current was: '" + pdbid
761               + "'");
762     }
763     if (errormsgs.length() > 0)
764     {
765
766       JOptionPane.showInternalMessageDialog(Desktop.desktop,
767               "The following pdb entries could not be retrieved from the PDB:\n"
768                       + errormsgs.toString()
769                       + "\nPlease try downloading them manually.",
770               "Couldn't load file", JOptionPane.ERROR_MESSAGE);
771
772     }
773     long lastnotify = jmb.getLoadNotifiesHandled();
774     if (files.length() > 0)
775     {
776       if (!addingStructures)
777       {
778
779         try
780         {
781           initJmol("load FILES " + files.toString());
782         } catch (OutOfMemoryError oomerror)
783         {
784           new OOMWarning("When trying to open the Jmol viewer!", oomerror);
785           Cache.log.debug("File locations are " + files);
786         } catch (Exception ex)
787         {
788           Cache.log.error("Couldn't open Jmol viewer!", ex);
789         }
790       }
791       else
792       {
793         StringBuffer cmd = new StringBuffer();
794         cmd.append("loadingJalviewdata=true\nload APPEND ");
795         cmd.append(files.toString());
796         cmd.append("\nloadingJalviewdata=null");
797         final String command = cmd.toString();
798         cmd = null;
799         lastnotify = jmb.getLoadNotifiesHandled();
800         
801         try
802         {
803           jmb.evalStateCommand(command);
804         } catch (OutOfMemoryError oomerror)
805         {
806           new OOMWarning(
807                   "When trying to add structures to the Jmol viewer!",
808                   oomerror);
809           Cache.log.debug("File locations are " + files);
810         } catch (Exception ex)
811         {
812           Cache.log.error("Couldn't add files to Jmol viewer!", ex);
813         }
814       }
815     
816       // need to wait around until script has finished
817       while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
818               : (jmb.isFinishedInit() && jmb.getPdbFile().length!=jmb.pdbentry.length))
819       {
820         try
821         {
822           Cache.log.debug("Waiting around for jmb notify.");
823           Thread.sleep(35);
824         } catch (Exception e)
825         {
826         }
827       }
828       // refresh the sequence colours for the new structure(s)
829       for (AlignmentPanel ap : _colourwith)
830       {
831         jmb.updateColours(ap);
832       }
833       // do superposition if asked to
834       if (alignAddedStructures)
835       {
836         javax.swing.SwingUtilities.invokeLater(new Runnable()
837         {
838           public void run()
839           {
840             alignStructs_withAllAlignPanels();
841             // jmb.superposeStructures(ap.av.getAlignment(), -1, null);
842           }
843         });
844         alignAddedStructures = false;
845       }
846       addingStructures = false;
847
848     }
849     _started = false;
850     worker = null;
851   }
852
853   public void pdbFile_actionPerformed(ActionEvent actionEvent)
854   {
855     JalviewFileChooser chooser = new JalviewFileChooser(
856             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
857
858     chooser.setFileView(new JalviewFileView());
859     chooser.setDialogTitle("Save PDB File");
860     chooser.setToolTipText("Save");
861
862     int value = chooser.showSaveDialog(this);
863
864     if (value == JalviewFileChooser.APPROVE_OPTION)
865     {
866       try
867       {
868         // TODO: cope with multiple PDB files in view
869         BufferedReader in = new BufferedReader(new FileReader(
870                 jmb.getPdbFile()[0]));
871         File outFile = chooser.getSelectedFile();
872
873         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
874         String data;
875         while ((data = in.readLine()) != null)
876         {
877           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
878           {
879             out.println(data);
880           }
881         }
882         out.close();
883       } catch (Exception ex)
884       {
885         ex.printStackTrace();
886       }
887     }
888   }
889
890   public void viewMapping_actionPerformed(ActionEvent actionEvent)
891   {
892     jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
893     try
894     {
895       for (int pdbe = 0; pdbe < jmb.pdbentry.length; pdbe++)
896       {
897         cap.appendText(jmb.printMapping(
898                         jmb.pdbentry[pdbe].getFile()));
899         cap.appendText("\n");
900       }
901     } catch (OutOfMemoryError e)
902     {
903       new OOMWarning(
904               "composing sequence-structure alignments for display in text box.",
905               e);
906       cap.dispose();
907       return;
908     }
909     jalview.gui.Desktop.addInternalFrame(cap, "PDB - Sequence Mapping",
910             550, 600);
911   }
912
913   /**
914    * DOCUMENT ME!
915    * 
916    * @param e
917    *          DOCUMENT ME!
918    */
919   public void eps_actionPerformed(ActionEvent e)
920   {
921     makePDBImage(jalview.util.ImageMaker.EPS);
922   }
923
924   /**
925    * DOCUMENT ME!
926    * 
927    * @param e
928    *          DOCUMENT ME!
929    */
930   public void png_actionPerformed(ActionEvent e)
931   {
932     makePDBImage(jalview.util.ImageMaker.PNG);
933   }
934
935   void makePDBImage(int type)
936   {
937     int width = getWidth();
938     int height = getHeight();
939
940     jalview.util.ImageMaker im;
941
942     if (type == jalview.util.ImageMaker.PNG)
943     {
944       im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.PNG,
945               "Make PNG image from view", width, height, null, null);
946     }
947     else
948     {
949       im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.EPS,
950               "Make EPS file from view", width, height, null,
951               this.getTitle());
952     }
953
954     if (im.getGraphics() != null)
955     {
956       Rectangle rect = new Rectangle(width, height);
957       jmb.viewer.renderScreenImage(im.getGraphics(), rect.getSize(), rect);
958       im.writeImage();
959     }
960   }
961   public void jmolColour_actionPerformed(ActionEvent actionEvent)
962   {
963     if (jmolColour.isSelected()) {
964       // disable automatic sequence colouring.
965       jmb.setColourBySequence(false);
966     }
967   }
968   public void seqColour_actionPerformed(ActionEvent actionEvent)
969   {
970     jmb.setColourBySequence(seqColour.isSelected());
971     if (_colourwith == null)
972     {
973       _colourwith = new Vector<AlignmentPanel>();
974     }
975     if (jmb.isColourBySequence())
976     {
977       if (!jmb.isLoadingFromArchive())
978       {
979         if (_colourwith.size()==0 && ap!=null) {
980           // Make the currently displayed alignment panel the associated view
981           _colourwith.add(ap.alignFrame.alignPanel);
982         }
983       }
984       // Set the colour using the current view for the associated alignframe
985       for (AlignmentPanel ap : _colourwith)
986       {
987         jmb.colourBySequence(ap.av.showSequenceFeatures, ap);
988       }
989     }
990   }
991
992   public void chainColour_actionPerformed(ActionEvent actionEvent)
993   {
994     chainColour.setSelected(true);
995     jmb.colourByChain();
996   }
997
998   public void chargeColour_actionPerformed(ActionEvent actionEvent)
999   {
1000     chargeColour.setSelected(true);
1001     jmb.colourByCharge();
1002   }
1003
1004   public void zappoColour_actionPerformed(ActionEvent actionEvent)
1005   {
1006     zappoColour.setSelected(true);
1007     jmb.setJalviewColourScheme(new ZappoColourScheme());
1008   }
1009
1010   public void taylorColour_actionPerformed(ActionEvent actionEvent)
1011   {
1012     taylorColour.setSelected(true);
1013     jmb.setJalviewColourScheme(new TaylorColourScheme());
1014   }
1015
1016   public void hydroColour_actionPerformed(ActionEvent actionEvent)
1017   {
1018     hydroColour.setSelected(true);
1019     jmb.setJalviewColourScheme(new HydrophobicColourScheme());
1020   }
1021
1022   public void helixColour_actionPerformed(ActionEvent actionEvent)
1023   {
1024     helixColour.setSelected(true);
1025     jmb.setJalviewColourScheme(new HelixColourScheme());
1026   }
1027
1028   public void strandColour_actionPerformed(ActionEvent actionEvent)
1029   {
1030     strandColour.setSelected(true);
1031     jmb.setJalviewColourScheme(new StrandColourScheme());
1032   }
1033
1034   public void turnColour_actionPerformed(ActionEvent actionEvent)
1035   {
1036     turnColour.setSelected(true);
1037     jmb.setJalviewColourScheme(new TurnColourScheme());
1038   }
1039
1040   public void buriedColour_actionPerformed(ActionEvent actionEvent)
1041   {
1042     buriedColour.setSelected(true);
1043     jmb.setJalviewColourScheme(new BuriedColourScheme());
1044   }
1045
1046   public void userColour_actionPerformed(ActionEvent actionEvent)
1047   {
1048     userColour.setSelected(true);
1049     new UserDefinedColours(this, null);
1050   }
1051
1052   public void backGround_actionPerformed(ActionEvent actionEvent)
1053   {
1054     java.awt.Color col = JColorChooser.showDialog(this,
1055             "Select Background Colour", null);
1056     if (col != null)
1057     {
1058       jmb.setBackgroundColour(col);
1059     }
1060   }
1061
1062   public void jmolHelp_actionPerformed(ActionEvent actionEvent)
1063   {
1064     try
1065     {
1066       jalview.util.BrowserLauncher
1067               .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
1068     } catch (Exception ex)
1069     {
1070     }
1071   }
1072
1073   public void showConsole(boolean showConsole)
1074   {
1075
1076     if (showConsole)
1077     {
1078       if (splitPane == null)
1079       {
1080         splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
1081         splitPane.setTopComponent(renderPanel);
1082         splitPane.setBottomComponent(scriptWindow);
1083         this.getContentPane().add(splitPane, BorderLayout.CENTER);
1084         splitPane.setDividerLocation(getHeight() - 200);
1085         scriptWindow.setVisible(true);
1086         scriptWindow.validate();
1087         splitPane.validate();
1088       }
1089
1090     }
1091     else
1092     {
1093       if (splitPane != null)
1094       {
1095         splitPane.setVisible(false);
1096       }
1097
1098       splitPane = null;
1099
1100       this.getContentPane().add(renderPanel, BorderLayout.CENTER);
1101     }
1102
1103     validate();
1104   }
1105
1106   class RenderPanel extends JPanel
1107   {
1108     final Dimension currentSize = new Dimension();
1109
1110     final Rectangle rectClip = new Rectangle();
1111
1112     public void paintComponent(Graphics g)
1113     {
1114       getSize(currentSize);
1115       g.getClipBounds(rectClip);
1116
1117       if (jmb.fileLoadingError != null)
1118       {
1119         g.setColor(Color.black);
1120         g.fillRect(0, 0, currentSize.width, currentSize.height);
1121         g.setColor(Color.white);
1122         g.setFont(new Font("Verdana", Font.BOLD, 14));
1123         g.drawString("Error loading file...", 20, currentSize.height / 2);
1124         StringBuffer sb = new StringBuffer();
1125         int lines = 0;
1126         for (int e = 0; e < jmb.pdbentry.length; e++)
1127         {
1128           sb.append(jmb.pdbentry[e].getId());
1129           if (e < jmb.pdbentry.length - 1)
1130           {
1131             sb.append(",");
1132           }
1133
1134           if (e == jmb.pdbentry.length - 1 || sb.length() > 20)
1135           {
1136             lines++;
1137             g.drawString(sb.toString(), 20, currentSize.height / 2 - lines
1138                     * g.getFontMetrics().getHeight());
1139           }
1140         }
1141       }
1142       else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
1143       {
1144         g.setColor(Color.black);
1145         g.fillRect(0, 0, currentSize.width, currentSize.height);
1146         g.setColor(Color.white);
1147         g.setFont(new Font("Verdana", Font.BOLD, 14));
1148         g.drawString("Retrieving PDB data....", 20, currentSize.height / 2);
1149       }
1150       else
1151       {
1152         jmb.viewer.renderScreenImage(g, currentSize, rectClip);
1153       }
1154     }
1155   }
1156
1157   String viewId = null;
1158
1159   public String getViewId()
1160   {
1161     if (viewId == null)
1162     {
1163       viewId = System.currentTimeMillis() + "." + this.hashCode();
1164     }
1165     return viewId;
1166   }
1167
1168   public void updateTitleAndMenus()
1169   {
1170     if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
1171     {
1172       repaint();
1173       return;
1174     }
1175     setChainMenuItems(jmb.chainNames);
1176
1177     this.setTitle(jmb.getViewerTitle());
1178     if (jmb.getPdbFile().length > 1 && jmb.sequence.length > 1)
1179     {
1180       jmolActionMenu.setVisible(true);
1181     }
1182     if (!jmb.isLoadingFromArchive())
1183     {
1184       seqColour_actionPerformed(null);
1185     }
1186   }
1187
1188   protected void buildJmolActionMenu()
1189   {
1190     if (_alignwith == null)
1191     {
1192       _alignwith = new Vector<AlignmentPanel>();
1193     }
1194     if (_alignwith.size() == 0 && ap != null)
1195     {
1196       _alignwith.add(ap);
1197     }
1198     ;
1199     for (Component c : jmolActionMenu.getMenuComponents())
1200     {
1201       if (c != alignStructs)
1202       {
1203         jmolActionMenu.remove((JMenuItem) c);
1204       }
1205     }
1206     final ItemListener handler;
1207   }
1208
1209   /*
1210    * (non-Javadoc)
1211    * 
1212    * @see
1213    * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
1214    * .ActionEvent)
1215    */
1216   @Override
1217   protected void alignStructs_actionPerformed(ActionEvent actionEvent)
1218   {
1219     alignStructs_withAllAlignPanels();
1220   }
1221
1222   private void alignStructs_withAllAlignPanels()
1223   {
1224     if (ap == null)
1225     {
1226       return;
1227     }
1228     ;
1229     if (_alignwith.size() == 0)
1230     {
1231       _alignwith.add(ap);
1232     }
1233     ;
1234     try
1235     {
1236       AlignmentI[] als = new Alignment[_alignwith.size()];
1237       ColumnSelection[] alc = new ColumnSelection[_alignwith.size()];
1238       int[] alm = new int[_alignwith.size()];
1239       int a = 0;
1240
1241       for (AlignmentPanel ap : _alignwith)
1242       {
1243         als[a] = ap.av.getAlignment();
1244         alm[a] = -1;
1245         alc[a++] = ap.av.getColumnSelection();
1246       }
1247       jmb.superposeStructures(als, alm, alc);
1248     } catch (Exception e)
1249     {
1250       StringBuffer sp = new StringBuffer();
1251       for (AlignmentPanel ap : _alignwith)
1252       {
1253         sp.append("'" + ap.alignFrame.getTitle() + "' ");
1254       }
1255       Cache.log.info("Couldn't align structures with the " + sp.toString()
1256               + "associated alignment panels.", e);
1257
1258     }
1259
1260   }
1261
1262   public void setJalviewColourScheme(ColourSchemeI ucs)
1263   {
1264     jmb.setJalviewColourScheme(ucs);
1265
1266   }
1267
1268   /**
1269    * 
1270    * @param alignment
1271    * @return first alignment panel displaying given alignment, or the default
1272    *         alignment panel
1273    */
1274   public AlignmentPanel getAlignmentPanelFor(AlignmentI alignment)
1275   {
1276     for (AlignmentPanel ap : getAllAlignmentPanels())
1277     {
1278       if (ap.av.getAlignment() == alignment)
1279       {
1280         return ap;
1281       }
1282     }
1283     return ap;
1284   }
1285
1286   /**
1287    * 
1288    * @param ap2
1289    * @return true if this Jmol instance is linked with the given alignPanel
1290    */
1291   public boolean isLinkedWith(AlignmentPanel ap2)
1292   {
1293     return _aps.contains(ap2.av.getSequenceSetId());
1294   }
1295
1296   public boolean isUsedforaligment(AlignmentPanel ap2)
1297   {
1298
1299     return (_alignwith != null) && _alignwith.contains(ap2);
1300   }
1301
1302   public boolean isUsedforcolourby(AlignmentPanel ap2)
1303   {
1304     return (_colourwith != null) && _colourwith.contains(ap2);
1305   }
1306
1307   /**
1308    * 
1309    * @return TRUE if the view is NOT being coloured by sequence associations.
1310    */
1311   public boolean isColouredByJmol()
1312   {
1313     return !jmb.isColourBySequence();
1314     }
1315   
1316
1317 }