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