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