f05a7d4d9e223bb4e173b82508af14a701b71e04
[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       jmb.viewer.renderScreenImage(im.getGraphics(), width, height);
905       im.writeImage();
906     }
907   }
908
909   @Override
910   public void viewerColour_actionPerformed(ActionEvent actionEvent)
911   {
912     if (viewerColour.isSelected())
913     {
914       // disable automatic sequence colouring.
915       jmb.setColourBySequence(false);
916     }
917   }
918
919   @Override
920   public void seqColour_actionPerformed(ActionEvent actionEvent)
921   {
922     jmb.setColourBySequence(seqColour.isSelected());
923     if (_colourwith == null)
924     {
925       _colourwith = new Vector<AlignmentPanel>();
926     }
927     if (jmb.isColourBySequence())
928     {
929       if (!jmb.isLoadingFromArchive())
930       {
931         if (_colourwith.size() == 0 && getAlignmentPanel() != null)
932         {
933           // Make the currently displayed alignment panel the associated view
934           _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
935         }
936       }
937       // Set the colour using the current view for the associated alignframe
938       for (AlignmentPanel ap : _colourwith)
939       {
940         jmb.colourBySequence(ap.av.isShowSequenceFeatures(), ap);
941       }
942     }
943   }
944
945   @Override
946   public void chainColour_actionPerformed(ActionEvent actionEvent)
947   {
948     chainColour.setSelected(true);
949     jmb.colourByChain();
950   }
951
952   @Override
953   public void chargeColour_actionPerformed(ActionEvent actionEvent)
954   {
955     chargeColour.setSelected(true);
956     jmb.colourByCharge();
957   }
958
959   @Override
960   public void zappoColour_actionPerformed(ActionEvent actionEvent)
961   {
962     zappoColour.setSelected(true);
963     jmb.setJalviewColourScheme(new ZappoColourScheme());
964   }
965
966   @Override
967   public void taylorColour_actionPerformed(ActionEvent actionEvent)
968   {
969     taylorColour.setSelected(true);
970     jmb.setJalviewColourScheme(new TaylorColourScheme());
971   }
972
973   @Override
974   public void hydroColour_actionPerformed(ActionEvent actionEvent)
975   {
976     hydroColour.setSelected(true);
977     jmb.setJalviewColourScheme(new HydrophobicColourScheme());
978   }
979
980   @Override
981   public void helixColour_actionPerformed(ActionEvent actionEvent)
982   {
983     helixColour.setSelected(true);
984     jmb.setJalviewColourScheme(new HelixColourScheme());
985   }
986
987   @Override
988   public void strandColour_actionPerformed(ActionEvent actionEvent)
989   {
990     strandColour.setSelected(true);
991     jmb.setJalviewColourScheme(new StrandColourScheme());
992   }
993
994   @Override
995   public void turnColour_actionPerformed(ActionEvent actionEvent)
996   {
997     turnColour.setSelected(true);
998     jmb.setJalviewColourScheme(new TurnColourScheme());
999   }
1000
1001   @Override
1002   public void buriedColour_actionPerformed(ActionEvent actionEvent)
1003   {
1004     buriedColour.setSelected(true);
1005     jmb.setJalviewColourScheme(new BuriedColourScheme());
1006   }
1007
1008   @Override
1009   public void purinePyrimidineColour_actionPerformed(ActionEvent actionEvent)
1010   {
1011     setJalviewColourScheme(new PurinePyrimidineColourScheme());
1012   }
1013
1014   @Override
1015   public void userColour_actionPerformed(ActionEvent actionEvent)
1016   {
1017     userColour.setSelected(true);
1018     new UserDefinedColours(this, null);
1019   }
1020
1021   @Override
1022   public void backGround_actionPerformed(ActionEvent actionEvent)
1023   {
1024     java.awt.Color col = JColorChooser.showDialog(this,
1025             MessageManager.getString("label.select_backgroud_colour"), null);
1026     if (col != null)
1027     {
1028       jmb.setBackgroundColour(col);
1029     }
1030   }
1031
1032   @Override
1033   public void showHelp_actionPerformed(ActionEvent actionEvent)
1034   {
1035     try
1036     {
1037       jalview.util.BrowserLauncher
1038               .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
1039     } catch (Exception ex)
1040     {
1041     }
1042   }
1043
1044   public void showConsole(boolean showConsole)
1045   {
1046
1047     if (showConsole)
1048     {
1049       if (splitPane == null)
1050       {
1051         splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
1052         splitPane.setTopComponent(renderPanel);
1053         splitPane.setBottomComponent(scriptWindow);
1054         this.getContentPane().add(splitPane, BorderLayout.CENTER);
1055         splitPane.setDividerLocation(getHeight() - 200);
1056         scriptWindow.setVisible(true);
1057         scriptWindow.validate();
1058         splitPane.validate();
1059       }
1060
1061     }
1062     else
1063     {
1064       if (splitPane != null)
1065       {
1066         splitPane.setVisible(false);
1067       }
1068
1069       splitPane = null;
1070
1071       this.getContentPane().add(renderPanel, BorderLayout.CENTER);
1072     }
1073
1074     validate();
1075   }
1076
1077   class RenderPanel extends JPanel
1078   {
1079     final Dimension currentSize = new Dimension();
1080
1081     @Override
1082     public void paintComponent(Graphics g)
1083     {
1084       getSize(currentSize);
1085
1086       if (jmb != null && jmb.fileLoadingError != null)
1087       {
1088         g.setColor(Color.black);
1089         g.fillRect(0, 0, currentSize.width, currentSize.height);
1090         g.setColor(Color.white);
1091         g.setFont(new Font("Verdana", Font.BOLD, 14));
1092         g.drawString(MessageManager.getString("label.error_loading_file")
1093                 + "...", 20, currentSize.height / 2);
1094         StringBuffer sb = new StringBuffer();
1095         int lines = 0;
1096         for (int e = 0; e < jmb.getPdbCount(); e++)
1097         {
1098           sb.append(jmb.getPdbEntry(e).getId());
1099           if (e < jmb.getPdbCount() - 1)
1100           {
1101             sb.append(",");
1102           }
1103
1104           if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
1105           {
1106             lines++;
1107             g.drawString(sb.toString(), 20, currentSize.height / 2 - lines
1108                     * g.getFontMetrics().getHeight());
1109           }
1110         }
1111       }
1112       else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
1113       {
1114         g.setColor(Color.black);
1115         g.fillRect(0, 0, currentSize.width, currentSize.height);
1116         g.setColor(Color.white);
1117         g.setFont(new Font("Verdana", Font.BOLD, 14));
1118         g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
1119                 20, currentSize.height / 2);
1120       }
1121       else
1122       {
1123         jmb.viewer.renderScreenImage(g, currentSize.width,
1124                 currentSize.height);
1125       }
1126     }
1127   }
1128
1129   public void updateTitleAndMenus()
1130   {
1131     if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
1132     {
1133       repaint();
1134       return;
1135     }
1136     setChainMenuItems(jmb.chainNames);
1137
1138     this.setTitle(jmb.getViewerTitle());
1139     if (jmb.getPdbFile().length > 1 && jmb.getSequence().length > 1)
1140     {
1141       viewerActionMenu.setVisible(true);
1142     }
1143     if (!jmb.isLoadingFromArchive())
1144     {
1145       seqColour_actionPerformed(null);
1146     }
1147   }
1148
1149   /*
1150    * (non-Javadoc)
1151    * 
1152    * @see
1153    * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
1154    * .ActionEvent)
1155    */
1156   @Override
1157   protected void alignStructs_actionPerformed(ActionEvent actionEvent)
1158   {
1159     alignStructs_withAllAlignPanels();
1160   }
1161
1162   private void alignStructs_withAllAlignPanels()
1163   {
1164     if (getAlignmentPanel() == null)
1165     {
1166       return;
1167     }
1168     ;
1169     if (_alignwith.size() == 0)
1170     {
1171       _alignwith.add(getAlignmentPanel());
1172     }
1173     ;
1174     try
1175     {
1176       AlignmentI[] als = new Alignment[_alignwith.size()];
1177       ColumnSelection[] alc = new ColumnSelection[_alignwith.size()];
1178       int[] alm = new int[_alignwith.size()];
1179       int a = 0;
1180
1181       for (AlignmentPanel ap : _alignwith)
1182       {
1183         als[a] = ap.av.getAlignment();
1184         alm[a] = -1;
1185         alc[a++] = ap.av.getColumnSelection();
1186       }
1187       jmb.superposeStructures(als, alm, alc);
1188     } catch (Exception e)
1189     {
1190       StringBuffer sp = new StringBuffer();
1191       for (AlignmentPanel ap : _alignwith)
1192       {
1193         sp.append("'" + ap.alignFrame.getTitle() + "' ");
1194       }
1195       Cache.log.info("Couldn't align structures with the " + sp.toString()
1196               + "associated alignment panels.", e);
1197
1198     }
1199
1200   }
1201
1202   public void setJalviewColourScheme(ColourSchemeI ucs)
1203   {
1204     jmb.setJalviewColourScheme(ucs);
1205
1206   }
1207
1208   /**
1209    * 
1210    * @param alignment
1211    * @return first alignment panel displaying given alignment, or the default
1212    *         alignment panel
1213    */
1214   public AlignmentPanel getAlignmentPanelFor(AlignmentI alignment)
1215   {
1216     for (AlignmentPanel ap : getAllAlignmentPanels())
1217     {
1218       if (ap.av.getAlignment() == alignment)
1219       {
1220         return ap;
1221       }
1222     }
1223     return getAlignmentPanel();
1224   }
1225
1226   @Override
1227   public AAStructureBindingModel getBinding()
1228   {
1229     return this.jmb;
1230   }
1231
1232   @Override
1233   public String getStateInfo()
1234   {
1235     return jmb == null ? null : jmb.viewer.getStateInfo();
1236   }
1237
1238   @Override
1239   public ViewerType getViewerType()
1240   {
1241     return ViewerType.JMOL;
1242   }
1243
1244 }