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