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