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