update author list in license for (JAL-826)
[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, J Engelhardt, LM Lui, 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     boolean promptUser=pdbentrys.length==1;
325     progressBar = ap.alignFrame;
326     jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(), pdbentrys, seqs, null, null);
327     addAlignmentPanel(ap);
328     useAlignmentPanelForColourbyseq(ap);
329     if (pdbentrys.length>1)
330     {
331       alignAddedStructures=true;
332       useAlignmentPanelForSuperposition(ap);
333     }
334     jmb.setColourBySequence(true);
335     setSize(400, 400); // probably should be a configurable/dynamic default here
336     initMenus();
337     worker=null;
338     String filelist="";
339 //    for (PDBEntry pe: pdbentrys)
340 //    {
341 //      if (pe.getFile()==null)
342       {
343         addingStructures = false;
344         worker = new Thread(this);
345         worker.start();
346 //        break;
347       }
348 //      filelist+=" \""+pe.getFile()+"\"";
349               
350 /*    }
351     if (worker==null)
352     {
353       initJmol("load"+(pdbentrys.length>1 ? " APPEND" : "") + filelist);
354     }
355 */
356     this.addInternalFrameListener(new InternalFrameAdapter()
357     {
358       public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
359       {
360         closeViewer();
361       }
362     });
363
364   }
365
366   /**
367    * create a new Jmol containing several structures superimposed using the given alignPanel.
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, boolean enableColourBySeq)
479   {
480     useAlignmentPanelForColourbyseq(nap);
481     jmb.setColourBySequence(enableColourBySeq);
482     seqColour.setSelected(enableColourBySeq);
483     jmolColour.setSelected(!enableColourBySeq);
484   }
485   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap)
486   {
487     addAlignmentPanel(nap);
488     if (!_colourwith.contains(nap))
489     {
490       _colourwith.add(nap);
491     }
492   }
493
494   public void excludeAlignmentPanelForColourbyseq(AlignmentPanel nap)
495   {
496     if (_colourwith.contains(nap))
497     {
498       _colourwith.remove(nap);
499     }
500   }
501
502   /**
503    * pdb retrieval thread.
504    */
505   private Thread worker = null;
506
507   /**
508    * add a new structure (with associated sequences and chains) to this viewer,
509    * retrieving it if necessary first.
510    * 
511    * @param pdbentry
512    * @param seq
513    * @param chains
514    * @param alignFrame
515    * @param align
516    *          if true, new structure(s) will be align using associated alignment
517    */
518   private void addStructure(final PDBEntry pdbentry, final SequenceI[] seq,
519           final String[] chains, final boolean b,
520           final IProgressIndicator alignFrame)
521   {
522     if (pdbentry.getFile() == null)
523     {
524       if (worker != null && worker.isAlive())
525       {
526         // a retrieval is in progress, wait around and add ourselves to the
527         // queue.
528         new Thread(new Runnable()
529         {
530           public void run()
531           {
532             while (worker != null && worker.isAlive() && _started)
533             {
534               try
535               {
536                 Thread.sleep(100 + ((int) Math.random() * 100));
537
538               } catch (Exception e)
539               {
540               }
541
542             }
543             // and call ourselves again.
544             addStructure(pdbentry, seq, chains, b, alignFrame);
545           }
546         }).start();
547         return;
548       }
549     }
550     // otherwise, start adding the structure.
551     jmb.addSequenceAndChain(new PDBEntry[]
552     { pdbentry }, new SequenceI[][]
553     { seq }, new String[][]
554     { chains });
555     addingStructures = true;
556     _started = false;
557     alignAddedStructures = b;
558     progressBar = alignFrame; // visual indication happens on caller frame.
559     (worker = new Thread(this)).start();
560     return;
561   }
562
563   private Vector getJmolsFor(AlignmentPanel ap2)
564   {
565     Vector otherJmols = new Vector();
566     // Now this AppJmol is mapped to new sequences. We must add them to
567     // the exisiting array
568     JInternalFrame[] frames = Desktop.instance.getAllFrames();
569
570     for (int i = 0; i < frames.length; i++)
571     {
572       if (frames[i] instanceof AppJmol)
573       {
574         AppJmol topJmol = ((AppJmol) frames[i]);
575         if (topJmol.isLinkedWith(ap2))
576         {
577           otherJmols.addElement(topJmol);
578         }
579       }
580     }
581     return otherJmols;
582   }
583
584   void initJmol(String command)
585   {
586     jmb.setFinishedInit(false);
587     renderPanel = new RenderPanel();
588     // TODO: consider waiting until the structure/view is fully loaded before
589     // displaying
590     this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
591     jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
592             getBounds().width, getBounds().height);
593     if (scriptWindow == null)
594     {
595       BorderLayout bl = new BorderLayout();
596       bl.setHgap(0);
597       bl.setVgap(0);
598       scriptWindow = new JPanel(bl);
599       scriptWindow.setVisible(false);
600     }
601     ;
602     jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
603             null);
604     jmb.newJmolPopup(true, "Jmol", true);
605     if (command==null)
606     {
607       command="";
608     }
609     jmb.evalStateCommand(command);
610     jmb.setFinishedInit(true);
611   }
612
613   void setChainMenuItems(Vector chains)
614   {
615     chainMenu.removeAll();
616     if (chains == null)
617     {
618       return;
619     }
620     JMenuItem menuItem = new JMenuItem("All");
621     menuItem.addActionListener(new ActionListener()
622     {
623       public void actionPerformed(ActionEvent evt)
624       {
625         allChainsSelected = true;
626         for (int i = 0; i < chainMenu.getItemCount(); i++)
627         {
628           if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
629             ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
630         }
631         centerViewer();
632         allChainsSelected = false;
633       }
634     });
635
636     chainMenu.add(menuItem);
637
638     for (int c = 0; c < chains.size(); c++)
639     {
640       menuItem = new JCheckBoxMenuItem(chains.elementAt(c).toString(), true);
641       menuItem.addItemListener(new ItemListener()
642       {
643         public void itemStateChanged(ItemEvent evt)
644         {
645           if (!allChainsSelected)
646             centerViewer();
647         }
648       });
649
650       chainMenu.add(menuItem);
651     }
652   }
653
654   boolean allChainsSelected = false;
655
656   private boolean alignAddedStructures = false;
657
658   void centerViewer()
659   {
660     Vector toshow = new Vector();
661     String lbl;
662     int mlength, p, mnum;
663     for (int i = 0; i < chainMenu.getItemCount(); i++)
664     {
665       if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
666       {
667         JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
668         if (item.isSelected())
669         {
670           toshow.addElement(item.getText());
671         }
672       }
673     }
674     jmb.centerViewer(toshow);
675   }
676
677   void closeViewer()
678   {
679     jmb.closeViewer();
680     ap = null;
681     _aps.clear();
682     _alignwith.clear();
683     _colourwith.clear();
684     // TODO: check for memory leaks where instance isn't finalised because jmb
685     // holds a reference to the window
686     jmb = null;
687   }
688
689   /**
690    * state flag for PDB retrieval thread
691    */
692   private boolean _started = false;
693
694   public void run()
695   {
696     _started = true;
697     String pdbid = "";
698     // todo - record which pdbids were successfuly imported.
699     StringBuffer errormsgs = new StringBuffer(), files = new StringBuffer();
700     try
701     {
702       String[] curfiles = jmb.getPdbFile(); // files currently in viewer
703       // TODO: replace with reference fetching/transfer code (validate PDBentry
704       // as a DBRef?)
705       jalview.ws.dbsources.Pdb pdbclient = new jalview.ws.dbsources.Pdb();
706       for (int pi = 0; pi < jmb.pdbentry.length; pi++)
707       {
708         String file = jmb.pdbentry[pi].getFile();
709         if (file == null)
710         {
711           // retrieve the pdb and store it locally
712           AlignmentI pdbseq = null;
713           pdbid = jmb.pdbentry[pi].getId();
714           long hdl = pdbid.hashCode() - System.currentTimeMillis();
715           if (progressBar != null)
716           {
717             progressBar.setProgressBar("Fetching PDB " + pdbid, hdl);
718           }
719           try
720           {
721             pdbseq = pdbclient.getSequenceRecords(pdbid = jmb.pdbentry[pi]
722                     .getId());
723           } catch (OutOfMemoryError oomerror)
724           {
725             new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
726           } catch (Exception ex)
727           {
728             ex.printStackTrace();
729             errormsgs.append("'" + pdbid + "'");
730           }
731           if (progressBar != null)
732           {
733             progressBar.setProgressBar("Finished.", hdl);
734           }
735           if (pdbseq != null)
736           {
737             // just transfer the file name from the first sequence's first
738             // PDBEntry
739             jmb.pdbentry[pi].setFile(file = ((PDBEntry) pdbseq
740                     .getSequenceAt(0).getPDBId().elementAt(0)).getFile());
741             files.append(" \"" + file + "\"");
742           }
743           else
744           {
745             errormsgs.append("'" + pdbid + "' ");
746           }
747         }
748         else
749         {
750           if (curfiles != null && curfiles.length > 0)
751           {
752             addingStructures = true; // already files loaded.
753             for (int c = 0; c < curfiles.length; c++)
754             {
755               if (curfiles[c].equals(file))
756               {
757                 file = null;
758                 break;
759               }
760             }
761           }
762           if (file != null)
763           {
764             files.append(" \"" + file + "\"");
765           }
766         }
767       }
768     } catch (OutOfMemoryError oomerror)
769     {
770       new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
771     } catch (Exception ex)
772     {
773       ex.printStackTrace();
774       errormsgs.append("When retrieving pdbfiles : current was: '" + pdbid
775               + "'");
776     }
777     if (errormsgs.length() > 0)
778     {
779
780       JOptionPane.showInternalMessageDialog(Desktop.desktop,
781               "The following pdb entries could not be retrieved from the PDB:\n"
782                       + errormsgs.toString()
783                       + "\nPlease try downloading them manually.",
784               "Couldn't load file", JOptionPane.ERROR_MESSAGE);
785
786     }
787     long lastnotify = jmb.getLoadNotifiesHandled();
788     if (files.length() > 0)
789     {
790       if (!addingStructures)
791       {
792
793         try
794         {
795           initJmol("load FILES " + files.toString());
796         } catch (OutOfMemoryError oomerror)
797         {
798           new OOMWarning("When trying to open the Jmol viewer!", oomerror);
799           Cache.log.debug("File locations are " + files);
800         } catch (Exception ex)
801         {
802           Cache.log.error("Couldn't open Jmol viewer!", ex);
803         }
804       }
805       else
806       {
807         StringBuffer cmd = new StringBuffer();
808         cmd.append("loadingJalviewdata=true\nload APPEND ");
809         cmd.append(files.toString());
810         cmd.append("\nloadingJalviewdata=null");
811         final String command = cmd.toString();
812         cmd = null;
813         lastnotify = jmb.getLoadNotifiesHandled();
814         
815         try
816         {
817           jmb.evalStateCommand(command);
818         } catch (OutOfMemoryError oomerror)
819         {
820           new OOMWarning(
821                   "When trying to add structures to the Jmol viewer!",
822                   oomerror);
823           Cache.log.debug("File locations are " + files);
824         } catch (Exception ex)
825         {
826           Cache.log.error("Couldn't add files to Jmol viewer!", ex);
827         }
828       }
829     
830       // need to wait around until script has finished
831       while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
832               : (jmb.isFinishedInit() && jmb.getPdbFile().length!=jmb.pdbentry.length))
833       {
834         try
835         {
836           Cache.log.debug("Waiting around for jmb notify.");
837           Thread.sleep(35);
838         } catch (Exception e)
839         {
840         }
841       }
842       // refresh the sequence colours for the new structure(s)
843       for (AlignmentPanel ap : _colourwith)
844       {
845         jmb.updateColours(ap);
846       }
847       // do superposition if asked to
848       if (alignAddedStructures)
849       {
850         javax.swing.SwingUtilities.invokeLater(new Runnable()
851         {
852           public void run()
853           {
854             alignStructs_withAllAlignPanels();
855             // jmb.superposeStructures(ap.av.getAlignment(), -1, null);
856           }
857         });
858         alignAddedStructures = false;
859       }
860       addingStructures = false;
861
862     }
863     _started = false;
864     worker = null;
865   }
866
867   public void pdbFile_actionPerformed(ActionEvent actionEvent)
868   {
869     JalviewFileChooser chooser = new JalviewFileChooser(
870             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
871
872     chooser.setFileView(new JalviewFileView());
873     chooser.setDialogTitle("Save PDB File");
874     chooser.setToolTipText("Save");
875
876     int value = chooser.showSaveDialog(this);
877
878     if (value == JalviewFileChooser.APPROVE_OPTION)
879     {
880       try
881       {
882         // TODO: cope with multiple PDB files in view
883         BufferedReader in = new BufferedReader(new FileReader(
884                 jmb.getPdbFile()[0]));
885         File outFile = chooser.getSelectedFile();
886
887         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
888         String data;
889         while ((data = in.readLine()) != null)
890         {
891           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
892           {
893             out.println(data);
894           }
895         }
896         out.close();
897       } catch (Exception ex)
898       {
899         ex.printStackTrace();
900       }
901     }
902   }
903
904   public void viewMapping_actionPerformed(ActionEvent actionEvent)
905   {
906     jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
907     try
908     {
909       for (int pdbe = 0; pdbe < jmb.pdbentry.length; pdbe++)
910       {
911         cap.appendText(jmb.printMapping(
912                         jmb.pdbentry[pdbe].getFile()));
913         cap.appendText("\n");
914       }
915     } catch (OutOfMemoryError e)
916     {
917       new OOMWarning(
918               "composing sequence-structure alignments for display in text box.",
919               e);
920       cap.dispose();
921       return;
922     }
923     jalview.gui.Desktop.addInternalFrame(cap, "PDB - Sequence Mapping",
924             550, 600);
925   }
926
927   /**
928    * DOCUMENT ME!
929    * 
930    * @param e
931    *          DOCUMENT ME!
932    */
933   public void eps_actionPerformed(ActionEvent e)
934   {
935     makePDBImage(jalview.util.ImageMaker.EPS);
936   }
937
938   /**
939    * DOCUMENT ME!
940    * 
941    * @param e
942    *          DOCUMENT ME!
943    */
944   public void png_actionPerformed(ActionEvent e)
945   {
946     makePDBImage(jalview.util.ImageMaker.PNG);
947   }
948
949   void makePDBImage(int type)
950   {
951     int width = getWidth();
952     int height = getHeight();
953
954     jalview.util.ImageMaker im;
955
956     if (type == jalview.util.ImageMaker.PNG)
957     {
958       im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.PNG,
959               "Make PNG image from view", width, height, null, null);
960     }
961     else
962     {
963       im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.EPS,
964               "Make EPS file from view", width, height, null,
965               this.getTitle());
966     }
967
968     if (im.getGraphics() != null)
969     {
970       Rectangle rect = new Rectangle(width, height);
971       jmb.viewer.renderScreenImage(im.getGraphics(), rect.getSize(), rect);
972       im.writeImage();
973     }
974   }
975   public void jmolColour_actionPerformed(ActionEvent actionEvent)
976   {
977     if (jmolColour.isSelected()) {
978       // disable automatic sequence colouring.
979       jmb.setColourBySequence(false);
980     }
981   }
982   public void seqColour_actionPerformed(ActionEvent actionEvent)
983   {
984     jmb.setColourBySequence(seqColour.isSelected());
985     if (_colourwith == null)
986     {
987       _colourwith = new Vector<AlignmentPanel>();
988     }
989     if (jmb.isColourBySequence())
990     {
991       if (!jmb.isLoadingFromArchive())
992       {
993         if (_colourwith.size()==0 && ap!=null) {
994           // Make the currently displayed alignment panel the associated view
995           _colourwith.add(ap.alignFrame.alignPanel);
996         }
997       }
998       // Set the colour using the current view for the associated alignframe
999       for (AlignmentPanel ap : _colourwith)
1000       {
1001         jmb.colourBySequence(ap.av.showSequenceFeatures, ap);
1002       }
1003     }
1004   }
1005
1006   public void chainColour_actionPerformed(ActionEvent actionEvent)
1007   {
1008     chainColour.setSelected(true);
1009     jmb.colourByChain();
1010   }
1011
1012   public void chargeColour_actionPerformed(ActionEvent actionEvent)
1013   {
1014     chargeColour.setSelected(true);
1015     jmb.colourByCharge();
1016   }
1017
1018   public void zappoColour_actionPerformed(ActionEvent actionEvent)
1019   {
1020     zappoColour.setSelected(true);
1021     jmb.setJalviewColourScheme(new ZappoColourScheme());
1022   }
1023
1024   public void taylorColour_actionPerformed(ActionEvent actionEvent)
1025   {
1026     taylorColour.setSelected(true);
1027     jmb.setJalviewColourScheme(new TaylorColourScheme());
1028   }
1029
1030   public void hydroColour_actionPerformed(ActionEvent actionEvent)
1031   {
1032     hydroColour.setSelected(true);
1033     jmb.setJalviewColourScheme(new HydrophobicColourScheme());
1034   }
1035
1036   public void helixColour_actionPerformed(ActionEvent actionEvent)
1037   {
1038     helixColour.setSelected(true);
1039     jmb.setJalviewColourScheme(new HelixColourScheme());
1040   }
1041
1042   public void strandColour_actionPerformed(ActionEvent actionEvent)
1043   {
1044     strandColour.setSelected(true);
1045     jmb.setJalviewColourScheme(new StrandColourScheme());
1046   }
1047
1048   public void turnColour_actionPerformed(ActionEvent actionEvent)
1049   {
1050     turnColour.setSelected(true);
1051     jmb.setJalviewColourScheme(new TurnColourScheme());
1052   }
1053
1054   public void buriedColour_actionPerformed(ActionEvent actionEvent)
1055   {
1056     buriedColour.setSelected(true);
1057     jmb.setJalviewColourScheme(new BuriedColourScheme());
1058   }
1059   
1060   public void purinePyrimidineColour_actionPerformed(ActionEvent actionEvent)
1061   {
1062     setJalviewColourScheme(new PurinePyrimidineColourScheme());
1063   }
1064   
1065   public void userColour_actionPerformed(ActionEvent actionEvent)
1066   {
1067     userColour.setSelected(true);
1068     new UserDefinedColours(this, null);
1069   }
1070
1071   public void backGround_actionPerformed(ActionEvent actionEvent)
1072   {
1073     java.awt.Color col = JColorChooser.showDialog(this,
1074             "Select Background Colour", null);
1075     if (col != null)
1076     {
1077       jmb.setBackgroundColour(col);
1078     }
1079   }
1080
1081   public void jmolHelp_actionPerformed(ActionEvent actionEvent)
1082   {
1083     try
1084     {
1085       jalview.util.BrowserLauncher
1086               .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
1087     } catch (Exception ex)
1088     {
1089     }
1090   }
1091
1092   public void showConsole(boolean showConsole)
1093   {
1094
1095     if (showConsole)
1096     {
1097       if (splitPane == null)
1098       {
1099         splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
1100         splitPane.setTopComponent(renderPanel);
1101         splitPane.setBottomComponent(scriptWindow);
1102         this.getContentPane().add(splitPane, BorderLayout.CENTER);
1103         splitPane.setDividerLocation(getHeight() - 200);
1104         scriptWindow.setVisible(true);
1105         scriptWindow.validate();
1106         splitPane.validate();
1107       }
1108
1109     }
1110     else
1111     {
1112       if (splitPane != null)
1113       {
1114         splitPane.setVisible(false);
1115       }
1116
1117       splitPane = null;
1118
1119       this.getContentPane().add(renderPanel, BorderLayout.CENTER);
1120     }
1121
1122     validate();
1123   }
1124
1125   class RenderPanel extends JPanel
1126   {
1127     final Dimension currentSize = new Dimension();
1128
1129     final Rectangle rectClip = new Rectangle();
1130
1131     public void paintComponent(Graphics g)
1132     {
1133       getSize(currentSize);
1134       g.getClipBounds(rectClip);
1135
1136       if (jmb.fileLoadingError != null)
1137       {
1138         g.setColor(Color.black);
1139         g.fillRect(0, 0, currentSize.width, currentSize.height);
1140         g.setColor(Color.white);
1141         g.setFont(new Font("Verdana", Font.BOLD, 14));
1142         g.drawString("Error loading file...", 20, currentSize.height / 2);
1143         StringBuffer sb = new StringBuffer();
1144         int lines = 0;
1145         for (int e = 0; e < jmb.pdbentry.length; e++)
1146         {
1147           sb.append(jmb.pdbentry[e].getId());
1148           if (e < jmb.pdbentry.length - 1)
1149           {
1150             sb.append(",");
1151           }
1152
1153           if (e == jmb.pdbentry.length - 1 || sb.length() > 20)
1154           {
1155             lines++;
1156             g.drawString(sb.toString(), 20, currentSize.height / 2 - lines
1157                     * g.getFontMetrics().getHeight());
1158           }
1159         }
1160       }
1161       else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
1162       {
1163         g.setColor(Color.black);
1164         g.fillRect(0, 0, currentSize.width, currentSize.height);
1165         g.setColor(Color.white);
1166         g.setFont(new Font("Verdana", Font.BOLD, 14));
1167         g.drawString("Retrieving PDB data....", 20, currentSize.height / 2);
1168       }
1169       else
1170       {
1171         jmb.viewer.renderScreenImage(g, currentSize, rectClip);
1172       }
1173     }
1174   }
1175
1176   String viewId = null;
1177
1178   public String getViewId()
1179   {
1180     if (viewId == null)
1181     {
1182       viewId = System.currentTimeMillis() + "." + this.hashCode();
1183     }
1184     return viewId;
1185   }
1186
1187   public void updateTitleAndMenus()
1188   {
1189     if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
1190     {
1191       repaint();
1192       return;
1193     }
1194     setChainMenuItems(jmb.chainNames);
1195
1196     this.setTitle(jmb.getViewerTitle());
1197     if (jmb.getPdbFile().length > 1 && jmb.sequence.length > 1)
1198     {
1199       jmolActionMenu.setVisible(true);
1200     }
1201     if (!jmb.isLoadingFromArchive())
1202     {
1203       seqColour_actionPerformed(null);
1204     }
1205   }
1206
1207   protected void buildJmolActionMenu()
1208   {
1209     if (_alignwith == null)
1210     {
1211       _alignwith = new Vector<AlignmentPanel>();
1212     }
1213     if (_alignwith.size() == 0 && ap != null)
1214     {
1215       _alignwith.add(ap);
1216     }
1217     ;
1218     for (Component c : jmolActionMenu.getMenuComponents())
1219     {
1220       if (c != alignStructs)
1221       {
1222         jmolActionMenu.remove((JMenuItem) c);
1223       }
1224     }
1225     final ItemListener handler;
1226   }
1227
1228   /*
1229    * (non-Javadoc)
1230    * 
1231    * @see
1232    * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
1233    * .ActionEvent)
1234    */
1235   @Override
1236   protected void alignStructs_actionPerformed(ActionEvent actionEvent)
1237   {
1238     alignStructs_withAllAlignPanels();
1239   }
1240
1241   private void alignStructs_withAllAlignPanels()
1242   {
1243     if (ap == null)
1244     {
1245       return;
1246     }
1247     ;
1248     if (_alignwith.size() == 0)
1249     {
1250       _alignwith.add(ap);
1251     }
1252     ;
1253     try
1254     {
1255       AlignmentI[] als = new Alignment[_alignwith.size()];
1256       ColumnSelection[] alc = new ColumnSelection[_alignwith.size()];
1257       int[] alm = new int[_alignwith.size()];
1258       int a = 0;
1259
1260       for (AlignmentPanel ap : _alignwith)
1261       {
1262         als[a] = ap.av.getAlignment();
1263         alm[a] = -1;
1264         alc[a++] = ap.av.getColumnSelection();
1265       }
1266       jmb.superposeStructures(als, alm, alc);
1267     } catch (Exception e)
1268     {
1269       StringBuffer sp = new StringBuffer();
1270       for (AlignmentPanel ap : _alignwith)
1271       {
1272         sp.append("'" + ap.alignFrame.getTitle() + "' ");
1273       }
1274       Cache.log.info("Couldn't align structures with the " + sp.toString()
1275               + "associated alignment panels.", e);
1276
1277     }
1278
1279   }
1280
1281   public void setJalviewColourScheme(ColourSchemeI ucs)
1282   {
1283     jmb.setJalviewColourScheme(ucs);
1284
1285   }
1286
1287   /**
1288    * 
1289    * @param alignment
1290    * @return first alignment panel displaying given alignment, or the default
1291    *         alignment panel
1292    */
1293   public AlignmentPanel getAlignmentPanelFor(AlignmentI alignment)
1294   {
1295     for (AlignmentPanel ap : getAllAlignmentPanels())
1296     {
1297       if (ap.av.getAlignment() == alignment)
1298       {
1299         return ap;
1300       }
1301     }
1302     return ap;
1303   }
1304
1305   /**
1306    * 
1307    * @param ap2
1308    * @return true if this Jmol instance is linked with the given alignPanel
1309    */
1310   public boolean isLinkedWith(AlignmentPanel ap2)
1311   {
1312     return _aps.contains(ap2.av.getSequenceSetId());
1313   }
1314
1315   public boolean isUsedforaligment(AlignmentPanel ap2)
1316   {
1317
1318     return (_alignwith != null) && _alignwith.contains(ap2);
1319   }
1320
1321   public boolean isUsedforcolourby(AlignmentPanel ap2)
1322   {
1323     return (_colourwith != null) && _colourwith.contains(ap2);
1324   }
1325
1326   /**
1327    * 
1328    * @return TRUE if the view is NOT being coloured by sequence associations.
1329    */
1330   public boolean isColouredByJmol()
1331   {
1332     return !jmb.isColourBySequence();
1333     }
1334   
1335
1336 }