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