JAL-2233 less verbose logging for Jmol
[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     /*
379      * -i for no info logging (less verbose)
380      */
381     jmb.allocateViewer(renderPanel, true, "", null, null, "-i",
382             scriptWindow, null);
383     // jmb.newJmolPopup("Jmol");
384     if (command == null)
385     {
386       command = "";
387     }
388     jmb.evalStateCommand(command);
389     jmb.evalStateCommand("set hoverDelay=0.1");
390     jmb.setFinishedInit(true);
391   }
392
393   void setChainMenuItems(Vector<String> chains)
394   {
395     chainMenu.removeAll();
396     if (chains == null)
397     {
398       return;
399     }
400     JMenuItem menuItem = new JMenuItem(
401             MessageManager.getString("label.all"));
402     menuItem.addActionListener(new ActionListener()
403     {
404       @Override
405       public void actionPerformed(ActionEvent evt)
406       {
407         allChainsSelected = true;
408         for (int i = 0; i < chainMenu.getItemCount(); i++)
409         {
410           if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
411           {
412             ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
413           }
414         }
415         centerViewer();
416         allChainsSelected = false;
417       }
418     });
419
420     chainMenu.add(menuItem);
421
422     for (String chain : chains)
423     {
424       menuItem = new JCheckBoxMenuItem(chain, true);
425       menuItem.addItemListener(new ItemListener()
426       {
427         @Override
428         public void itemStateChanged(ItemEvent evt)
429         {
430           if (!allChainsSelected)
431           {
432             centerViewer();
433           }
434         }
435       });
436
437       chainMenu.add(menuItem);
438     }
439   }
440
441   boolean allChainsSelected = false;
442
443   void centerViewer()
444   {
445     Vector<String> toshow = new Vector<String>();
446     for (int i = 0; i < chainMenu.getItemCount(); i++)
447     {
448       if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
449       {
450         JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
451         if (item.isSelected())
452         {
453           toshow.addElement(item.getText());
454         }
455       }
456     }
457     jmb.centerViewer(toshow);
458   }
459
460   @Override
461   public void closeViewer(boolean closeExternalViewer)
462   {
463     // Jmol does not use an external viewer
464     if (jmb != null)
465     {
466       jmb.closeViewer();
467     }
468     setAlignmentPanel(null);
469     _aps.clear();
470     _alignwith.clear();
471     _colourwith.clear();
472     // TODO: check for memory leaks where instance isn't finalised because jmb
473     // holds a reference to the window
474     jmb = null;
475   }
476
477   @Override
478   public void run()
479   {
480     _started = true;
481     String pdbid = "";
482     // todo - record which pdbids were successfuly imported.
483     StringBuffer errormsgs = new StringBuffer(), files = new StringBuffer();
484     try
485     {
486       String[] curfiles = jmb.getPdbFile(); // files currently in viewer
487       // TODO: replace with reference fetching/transfer code (validate PDBentry
488       // as a DBRef?)
489       jalview.ws.dbsources.Pdb pdbclient = new jalview.ws.dbsources.Pdb();
490       for (int pi = 0; pi < jmb.getPdbCount(); pi++)
491       {
492         String file = jmb.getPdbEntry(pi).getFile();
493         if (file == null)
494         {
495           // retrieve the pdb and store it locally
496           AlignmentI pdbseq = null;
497           pdbid = jmb.getPdbEntry(pi).getId();
498           long hdl = pdbid.hashCode() - System.currentTimeMillis();
499           if (progressBar != null)
500           {
501             progressBar.setProgressBar(MessageManager.formatMessage(
502                     "status.fetching_pdb", new String[] { pdbid }), hdl);
503           }
504           try
505           {
506             pdbseq = pdbclient.getSequenceRecords(pdbid);
507           } catch (OutOfMemoryError oomerror)
508           {
509             new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
510           } catch (Exception ex)
511           {
512             ex.printStackTrace();
513             errormsgs.append("'" + pdbid + "'");
514           }
515           if (progressBar != null)
516           {
517             progressBar.setProgressBar(
518                     MessageManager.getString("label.state_completed"), hdl);
519           }
520           if (pdbseq != null)
521           {
522             // just transfer the file name from the first sequence's first
523             // PDBEntry
524             file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
525                     .elementAt(0).getFile()).getAbsolutePath();
526             jmb.getPdbEntry(pi).setFile(file);
527
528             files.append(" \"" + Platform.escapeString(file) + "\"");
529           }
530           else
531           {
532             errormsgs.append("'" + pdbid + "' ");
533           }
534         }
535         else
536         {
537           if (curfiles != null && curfiles.length > 0)
538           {
539             addingStructures = true; // already files loaded.
540             for (int c = 0; c < curfiles.length; c++)
541             {
542               if (curfiles[c].equals(file))
543               {
544                 file = null;
545                 break;
546               }
547             }
548           }
549           if (file != null)
550           {
551             files.append(" \"" + Platform.escapeString(file) + "\"");
552           }
553         }
554       }
555     } catch (OutOfMemoryError oomerror)
556     {
557       new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
558     } catch (Exception ex)
559     {
560       ex.printStackTrace();
561       errormsgs.append("When retrieving pdbfiles : current was: '" + pdbid
562               + "'");
563     }
564     if (errormsgs.length() > 0)
565     {
566
567       JOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
568               .formatMessage("label.pdb_entries_couldnt_be_retrieved",
569                       new String[] { errormsgs.toString() }),
570               MessageManager.getString("label.couldnt_load_file"),
571               JOptionPane.ERROR_MESSAGE);
572
573     }
574     long lastnotify = jmb.getLoadNotifiesHandled();
575     if (files.length() > 0)
576     {
577       if (!addingStructures)
578       {
579
580         try
581         {
582           initJmol("load FILES " + files.toString());
583         } catch (OutOfMemoryError oomerror)
584         {
585           new OOMWarning("When trying to open the Jmol viewer!", oomerror);
586           Cache.log.debug("File locations are " + files);
587         } catch (Exception ex)
588         {
589           Cache.log.error("Couldn't open Jmol viewer!", ex);
590         }
591       }
592       else
593       {
594         StringBuffer cmd = new StringBuffer();
595         cmd.append("loadingJalviewdata=true\nload APPEND ");
596         cmd.append(files.toString());
597         cmd.append("\nloadingJalviewdata=null");
598         final String command = cmd.toString();
599         cmd = null;
600         lastnotify = jmb.getLoadNotifiesHandled();
601
602         try
603         {
604           jmb.evalStateCommand(command);
605         } catch (OutOfMemoryError oomerror)
606         {
607           new OOMWarning(
608                   "When trying to add structures to the Jmol viewer!",
609                   oomerror);
610           Cache.log.debug("File locations are " + files);
611         } catch (Exception ex)
612         {
613           Cache.log.error("Couldn't add files to Jmol viewer!", ex);
614         }
615       }
616
617       // need to wait around until script has finished
618       while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
619               : (!jmb.isFinishedInit() && jmb.getPdbFile() != null && jmb
620                       .getPdbFile().length != jmb.getPdbCount()))
621       {
622         try
623         {
624           Cache.log.debug("Waiting around for jmb notify.");
625           Thread.sleep(35);
626         } catch (Exception e)
627         {
628         }
629       }
630
631       // refresh the sequence colours for the new structure(s)
632       for (AlignmentPanel ap : _colourwith)
633       {
634         jmb.updateColours(ap);
635       }
636       // do superposition if asked to
637       if (Cache.getDefault("AUTOSUPERIMPOSE", true) && alignAddedStructures)
638       {
639         javax.swing.SwingUtilities.invokeLater(new Runnable()
640         {
641           @Override
642           public void run()
643           {
644             if (jmb.viewer.isScriptExecuting())
645             {
646               javax.swing.SwingUtilities.invokeLater(this);
647               try
648               {
649                 Thread.sleep(5);
650               } catch (InterruptedException q)
651               {
652               }
653               ;
654               return;
655             }
656             else
657             {
658               alignStructs_withAllAlignPanels();
659             }
660           }
661         });
662         alignAddedStructures = false;
663       }
664       addingStructures = false;
665
666     }
667     _started = false;
668     worker = null;
669   }
670
671   @Override
672   public void pdbFile_actionPerformed(ActionEvent actionEvent)
673   {
674     JalviewFileChooser chooser = new JalviewFileChooser(
675             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
676
677     chooser.setFileView(new JalviewFileView());
678     chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
679     chooser.setToolTipText(MessageManager.getString("action.save"));
680
681     int value = chooser.showSaveDialog(this);
682
683     if (value == JalviewFileChooser.APPROVE_OPTION)
684     {
685       BufferedReader in = null;
686       try
687       {
688         // TODO: cope with multiple PDB files in view
689         in = new BufferedReader(new FileReader(jmb.getPdbFile()[0]));
690         File outFile = chooser.getSelectedFile();
691
692         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
693         String data;
694         while ((data = in.readLine()) != null)
695         {
696           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
697           {
698             out.println(data);
699           }
700         }
701         out.close();
702       } catch (Exception ex)
703       {
704         ex.printStackTrace();
705       } finally
706       {
707         if (in != null)
708         {
709           try
710           {
711             in.close();
712           } catch (IOException e)
713           {
714             // ignore
715           }
716         }
717       }
718     }
719   }
720
721   @Override
722   public void viewMapping_actionPerformed(ActionEvent actionEvent)
723   {
724     jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
725     try
726     {
727       cap.appendText(jmb.printMappings());
728     } catch (OutOfMemoryError e)
729     {
730       new OOMWarning(
731               "composing sequence-structure alignments for display in text box.",
732               e);
733       cap.dispose();
734       return;
735     }
736     jalview.gui.Desktop.addInternalFrame(cap,
737             MessageManager.getString("label.pdb_sequence_mapping"), 550,
738             600);
739   }
740
741   @Override
742   public void eps_actionPerformed(ActionEvent e)
743   {
744     makePDBImage(jalview.util.ImageMaker.TYPE.EPS);
745   }
746
747   @Override
748   public void png_actionPerformed(ActionEvent e)
749   {
750     makePDBImage(jalview.util.ImageMaker.TYPE.PNG);
751   }
752
753   void makePDBImage(jalview.util.ImageMaker.TYPE type)
754   {
755     int width = getWidth();
756     int height = getHeight();
757
758     jalview.util.ImageMaker im;
759
760     if (type == jalview.util.ImageMaker.TYPE.PNG)
761     {
762       im = new jalview.util.ImageMaker(this,
763               jalview.util.ImageMaker.TYPE.PNG, "Make PNG image from view",
764               width, height, null, null, null, 0, false);
765     }
766     else if (type == jalview.util.ImageMaker.TYPE.EPS)
767     {
768       im = new jalview.util.ImageMaker(this,
769               jalview.util.ImageMaker.TYPE.EPS, "Make EPS file from view",
770               width, height, null, this.getTitle(), null, 0, false);
771     }
772     else
773     {
774
775       im = new jalview.util.ImageMaker(this,
776               jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
777               width, height, null, this.getTitle(), null, 0, false);
778     }
779
780     if (im.getGraphics() != null)
781     {
782       jmb.viewer.renderScreenImage(im.getGraphics(), width, height);
783       im.writeImage();
784     }
785   }
786
787   @Override
788   public void viewerColour_actionPerformed(ActionEvent actionEvent)
789   {
790     if (viewerColour.isSelected())
791     {
792       // disable automatic sequence colouring.
793       jmb.setColourBySequence(false);
794     }
795   }
796
797   @Override
798   public void seqColour_actionPerformed(ActionEvent actionEvent)
799   {
800     jmb.setColourBySequence(seqColour.isSelected());
801     if (_colourwith == null)
802     {
803       _colourwith = new Vector<AlignmentPanel>();
804     }
805     if (jmb.isColourBySequence())
806     {
807       if (!jmb.isLoadingFromArchive())
808       {
809         if (_colourwith.size() == 0 && getAlignmentPanel() != null)
810         {
811           // Make the currently displayed alignment panel the associated view
812           _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
813         }
814       }
815       // Set the colour using the current view for the associated alignframe
816       for (AlignmentPanel ap : _colourwith)
817       {
818         jmb.colourBySequence(ap);
819       }
820     }
821   }
822
823   @Override
824   public void chainColour_actionPerformed(ActionEvent actionEvent)
825   {
826     chainColour.setSelected(true);
827     jmb.colourByChain();
828   }
829
830   @Override
831   public void chargeColour_actionPerformed(ActionEvent actionEvent)
832   {
833     chargeColour.setSelected(true);
834     jmb.colourByCharge();
835   }
836
837   @Override
838   public void zappoColour_actionPerformed(ActionEvent actionEvent)
839   {
840     zappoColour.setSelected(true);
841     jmb.setJalviewColourScheme(new ZappoColourScheme());
842   }
843
844   @Override
845   public void taylorColour_actionPerformed(ActionEvent actionEvent)
846   {
847     taylorColour.setSelected(true);
848     jmb.setJalviewColourScheme(new TaylorColourScheme());
849   }
850
851   @Override
852   public void hydroColour_actionPerformed(ActionEvent actionEvent)
853   {
854     hydroColour.setSelected(true);
855     jmb.setJalviewColourScheme(new HydrophobicColourScheme());
856   }
857
858   @Override
859   public void helixColour_actionPerformed(ActionEvent actionEvent)
860   {
861     helixColour.setSelected(true);
862     jmb.setJalviewColourScheme(new HelixColourScheme());
863   }
864
865   @Override
866   public void strandColour_actionPerformed(ActionEvent actionEvent)
867   {
868     strandColour.setSelected(true);
869     jmb.setJalviewColourScheme(new StrandColourScheme());
870   }
871
872   @Override
873   public void turnColour_actionPerformed(ActionEvent actionEvent)
874   {
875     turnColour.setSelected(true);
876     jmb.setJalviewColourScheme(new TurnColourScheme());
877   }
878
879   @Override
880   public void buriedColour_actionPerformed(ActionEvent actionEvent)
881   {
882     buriedColour.setSelected(true);
883     jmb.setJalviewColourScheme(new BuriedColourScheme());
884   }
885
886   @Override
887   public void purinePyrimidineColour_actionPerformed(ActionEvent actionEvent)
888   {
889     setJalviewColourScheme(new PurinePyrimidineColourScheme());
890   }
891
892   @Override
893   public void userColour_actionPerformed(ActionEvent actionEvent)
894   {
895     userColour.setSelected(true);
896     new UserDefinedColours(this, null);
897   }
898
899   @Override
900   public void backGround_actionPerformed(ActionEvent actionEvent)
901   {
902     java.awt.Color col = JColorChooser
903             .showDialog(this, MessageManager
904                     .getString("label.select_backgroud_colour"), null);
905     if (col != null)
906     {
907       jmb.setBackgroundColour(col);
908     }
909   }
910
911   @Override
912   public void showHelp_actionPerformed(ActionEvent actionEvent)
913   {
914     try
915     {
916       jalview.util.BrowserLauncher
917               .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
918     } catch (Exception ex)
919     {
920     }
921   }
922
923   public void showConsole(boolean showConsole)
924   {
925
926     if (showConsole)
927     {
928       if (splitPane == null)
929       {
930         splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
931         splitPane.setTopComponent(renderPanel);
932         splitPane.setBottomComponent(scriptWindow);
933         this.getContentPane().add(splitPane, BorderLayout.CENTER);
934         splitPane.setDividerLocation(getHeight() - 200);
935         scriptWindow.setVisible(true);
936         scriptWindow.validate();
937         splitPane.validate();
938       }
939
940     }
941     else
942     {
943       if (splitPane != null)
944       {
945         splitPane.setVisible(false);
946       }
947
948       splitPane = null;
949
950       this.getContentPane().add(renderPanel, BorderLayout.CENTER);
951     }
952
953     validate();
954   }
955
956   class RenderPanel extends JPanel
957   {
958     final Dimension currentSize = new Dimension();
959
960     @Override
961     public void paintComponent(Graphics g)
962     {
963       getSize(currentSize);
964
965       if (jmb != null && jmb.fileLoadingError != null)
966       {
967         g.setColor(Color.black);
968         g.fillRect(0, 0, currentSize.width, currentSize.height);
969         g.setColor(Color.white);
970         g.setFont(new Font("Verdana", Font.BOLD, 14));
971         g.drawString(MessageManager.getString("label.error_loading_file")
972                 + "...", 20, currentSize.height / 2);
973         StringBuffer sb = new StringBuffer();
974         int lines = 0;
975         for (int e = 0; e < jmb.getPdbCount(); e++)
976         {
977           sb.append(jmb.getPdbEntry(e).getId());
978           if (e < jmb.getPdbCount() - 1)
979           {
980             sb.append(",");
981           }
982
983           if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
984           {
985             lines++;
986             g.drawString(sb.toString(), 20, currentSize.height / 2 - lines
987                     * g.getFontMetrics().getHeight());
988           }
989         }
990       }
991       else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
992       {
993         g.setColor(Color.black);
994         g.fillRect(0, 0, currentSize.width, currentSize.height);
995         g.setColor(Color.white);
996         g.setFont(new Font("Verdana", Font.BOLD, 14));
997         g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
998                 20, currentSize.height / 2);
999       }
1000       else
1001       {
1002         jmb.viewer.renderScreenImage(g, currentSize.width,
1003                 currentSize.height);
1004       }
1005     }
1006   }
1007
1008   public void updateTitleAndMenus()
1009   {
1010     if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
1011     {
1012       repaint();
1013       return;
1014     }
1015     setChainMenuItems(jmb.chainNames);
1016
1017     this.setTitle(jmb.getViewerTitle());
1018     if (jmb.getPdbFile().length > 1 && jmb.getSequence().length > 1)
1019     {
1020       viewerActionMenu.setVisible(true);
1021     }
1022     if (!jmb.isLoadingFromArchive())
1023     {
1024       seqColour_actionPerformed(null);
1025     }
1026   }
1027
1028   /*
1029    * (non-Javadoc)
1030    * 
1031    * @see
1032    * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
1033    * .ActionEvent)
1034    */
1035   @Override
1036   protected void alignStructs_actionPerformed(ActionEvent actionEvent)
1037   {
1038     alignStructs_withAllAlignPanels();
1039   }
1040
1041   private void alignStructs_withAllAlignPanels()
1042   {
1043     if (getAlignmentPanel() == null)
1044     {
1045       return;
1046     }
1047     ;
1048     if (_alignwith.size() == 0)
1049     {
1050       _alignwith.add(getAlignmentPanel());
1051     }
1052     ;
1053     try
1054     {
1055       AlignmentI[] als = new Alignment[_alignwith.size()];
1056       ColumnSelection[] alc = new ColumnSelection[_alignwith.size()];
1057       int[] alm = new int[_alignwith.size()];
1058       int a = 0;
1059
1060       for (AlignmentPanel ap : _alignwith)
1061       {
1062         als[a] = ap.av.getAlignment();
1063         alm[a] = -1;
1064         alc[a++] = ap.av.getColumnSelection();
1065       }
1066       jmb.superposeStructures(als, alm, alc);
1067     } catch (Exception e)
1068     {
1069       StringBuffer sp = new StringBuffer();
1070       for (AlignmentPanel ap : _alignwith)
1071       {
1072         sp.append("'" + ap.alignFrame.getTitle() + "' ");
1073       }
1074       Cache.log.info("Couldn't align structures with the " + sp.toString()
1075               + "associated alignment panels.", e);
1076
1077     }
1078
1079   }
1080
1081   @Override
1082   public void setJalviewColourScheme(ColourSchemeI ucs)
1083   {
1084     jmb.setJalviewColourScheme(ucs);
1085
1086   }
1087
1088   /**
1089    * 
1090    * @param alignment
1091    * @return first alignment panel displaying given alignment, or the default
1092    *         alignment panel
1093    */
1094   public AlignmentPanel getAlignmentPanelFor(AlignmentI alignment)
1095   {
1096     for (AlignmentPanel ap : getAllAlignmentPanels())
1097     {
1098       if (ap.av.getAlignment() == alignment)
1099       {
1100         return ap;
1101       }
1102     }
1103     return getAlignmentPanel();
1104   }
1105
1106   @Override
1107   public AAStructureBindingModel getBinding()
1108   {
1109     return this.jmb;
1110   }
1111
1112   @Override
1113   public String getStateInfo()
1114   {
1115     return jmb == null ? null : jmb.viewer.getStateInfo();
1116   }
1117
1118   @Override
1119   public ViewerType getViewerType()
1120   {
1121     return ViewerType.JMOL;
1122   }
1123
1124   @Override
1125   protected AAStructureBindingModel getBindingModel()
1126   {
1127     return jmb;
1128   }
1129
1130 }