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