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