2299c2602b767098e161817d5615d4481337545e
[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).append(Platform.escapeString(s))
515               .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(
548                 "When trying to add structures to the Jmol viewer!",
549                 oomerror);
550         Cache.log.debug("File locations are " + filesString);
551       } catch (Exception ex)
552       {
553         Cache.log.error("Couldn't add files to Jmol viewer!", ex);
554       }
555     }
556
557     // need to wait around until script has finished
558     int waitMax = 5000; // give up after 5 seconds
559     int waitFor = 35;
560     int waitTotal = 0;
561     while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
562             : !(jmb.isFinishedInit() && jmb.getPdbFile() != null && jmb
563                     .getPdbFile().length == files.size()))
564     {
565       try
566       {
567         Cache.log.debug("Waiting around for jmb notify.");
568         Thread.sleep(waitFor);
569         waitTotal += waitFor;
570       } catch (Exception e)
571       {
572       }
573       if (waitTotal > waitMax)
574       {
575         System.err.println("Timed out waiting for Jmol to load files");
576         break;
577       }
578     }
579
580     // refresh the sequence colours for the new structure(s)
581     for (AlignmentPanel ap : _colourwith)
582     {
583       jmb.updateColours(ap);
584     }
585     // do superposition if asked to
586     if (Cache.getDefault("AUTOSUPERIMPOSE", true) && alignAddedStructures)
587     {
588       alignAddedStructures();
589     }
590     addingStructures = false;
591   }
592
593   /**
594    * Queues a thread to align structures with Jalview alignments
595    */
596   void alignAddedStructures()
597   {
598     javax.swing.SwingUtilities.invokeLater(new Runnable()
599     {
600       @Override
601       public void run()
602       {
603         if (jmb.viewer.isScriptExecuting())
604         {
605           SwingUtilities.invokeLater(this);
606           try
607           {
608             Thread.sleep(5);
609           } catch (InterruptedException q)
610           {
611           }
612           return;
613         }
614         else
615         {
616           alignStructs_withAllAlignPanels();
617         }
618       }
619     });
620     alignAddedStructures = false;
621   }
622
623   /**
624    * Retrieves and saves as file any modelled PDB entries for which we do not
625    * already have a file saved. Returns a list of absolute paths to structure
626    * files which were either retrieved, or already stored but not modelled in
627    * the structure viewer (i.e. files to add to the viewer display).
628    * 
629    * @return
630    */
631   List<String> fetchPdbFiles()
632   {
633     // todo - record which pdbids were successfully imported.
634     StringBuilder errormsgs = new StringBuilder();
635
636     List<String> files = new ArrayList<String>();
637     String pdbid = "";
638     try
639     {
640       String[] filesInViewer = jmb.getPdbFile();
641       // TODO: replace with reference fetching/transfer code (validate PDBentry
642       // as a DBRef?)
643       Pdb pdbclient = new Pdb();
644       for (int pi = 0; pi < jmb.getPdbCount(); pi++)
645       {
646         String file = jmb.getPdbEntry(pi).getFile();
647         if (file == null)
648         {
649           // retrieve the pdb and store it locally
650           AlignmentI pdbseq = null;
651           pdbid = jmb.getPdbEntry(pi).getId();
652           long hdl = pdbid.hashCode() - System.currentTimeMillis();
653           if (progressBar != null)
654           {
655             progressBar.setProgressBar(MessageManager.formatMessage(
656                     "status.fetching_pdb", new String[] { pdbid }), hdl);
657           }
658           try
659           {
660             pdbseq = pdbclient.getSequenceRecords(pdbid);
661           } catch (OutOfMemoryError oomerror)
662           {
663             new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
664           } catch (Exception ex)
665           {
666             ex.printStackTrace();
667             errormsgs.append("'").append(pdbid).append("'");
668           } finally
669           {
670             if (progressBar != null)
671             {
672               progressBar.setProgressBar(
673                       MessageManager.getString("label.state_completed"),
674                       hdl);
675             }
676           }
677           if (pdbseq != null)
678           {
679             // just transfer the file name from the first sequence's first
680             // PDBEntry
681             file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
682                     .elementAt(0).getFile()).getAbsolutePath();
683             jmb.getPdbEntry(pi).setFile(file);
684             files.add(file);
685           }
686           else
687           {
688             errormsgs.append("'").append(pdbid).append("' ");
689           }
690         }
691         else
692         {
693           if (filesInViewer != null && filesInViewer.length > 0)
694           {
695             addingStructures = true; // already files loaded.
696             for (int c = 0; c < filesInViewer.length; c++)
697             {
698               if (filesInViewer[c].equals(file))
699               {
700                 file = null;
701                 break;
702               }
703             }
704           }
705           if (file != null)
706           {
707             files.add(file);
708           }
709         }
710       }
711     } catch (OutOfMemoryError oomerror)
712     {
713       new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
714     } catch (Exception ex)
715     {
716       ex.printStackTrace();
717       errormsgs.append("When retrieving pdbfiles : current was: '")
718               .append(pdbid).append("'");
719     }
720     if (errormsgs.length() > 0)
721     {
722       JOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
723               .formatMessage("label.pdb_entries_couldnt_be_retrieved",
724                       new String[] { errormsgs.toString() }),
725               MessageManager.getString("label.couldnt_load_file"),
726               JOptionPane.ERROR_MESSAGE);
727     }
728     return files;
729   }
730
731   @Override
732   public void pdbFile_actionPerformed(ActionEvent actionEvent)
733   {
734     JalviewFileChooser chooser = new JalviewFileChooser(
735             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
736
737     chooser.setFileView(new JalviewFileView());
738     chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
739     chooser.setToolTipText(MessageManager.getString("action.save"));
740
741     int value = chooser.showSaveDialog(this);
742
743     if (value == JalviewFileChooser.APPROVE_OPTION)
744     {
745       BufferedReader in = null;
746       try
747       {
748         // TODO: cope with multiple PDB files in view
749         in = new BufferedReader(new FileReader(jmb.getPdbFile()[0]));
750         File outFile = chooser.getSelectedFile();
751
752         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
753         String data;
754         while ((data = in.readLine()) != null)
755         {
756           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
757           {
758             out.println(data);
759           }
760         }
761         out.close();
762       } catch (Exception ex)
763       {
764         ex.printStackTrace();
765       } finally
766       {
767         if (in != null)
768         {
769           try
770           {
771             in.close();
772           } catch (IOException e)
773           {
774             // ignore
775           }
776         }
777       }
778     }
779   }
780
781   @Override
782   public void viewMapping_actionPerformed(ActionEvent actionEvent)
783   {
784     jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
785     try
786     {
787       cap.appendText(jmb.printMappings());
788     } catch (OutOfMemoryError e)
789     {
790       new OOMWarning(
791               "composing sequence-structure alignments for display in text box.",
792               e);
793       cap.dispose();
794       return;
795     }
796     jalview.gui.Desktop.addInternalFrame(cap,
797             MessageManager.getString("label.pdb_sequence_mapping"), 550,
798             600);
799   }
800
801   @Override
802   public void eps_actionPerformed(ActionEvent e)
803   {
804     makePDBImage(jalview.util.ImageMaker.TYPE.EPS);
805   }
806
807   @Override
808   public void png_actionPerformed(ActionEvent e)
809   {
810     makePDBImage(jalview.util.ImageMaker.TYPE.PNG);
811   }
812
813   void makePDBImage(jalview.util.ImageMaker.TYPE type)
814   {
815     int width = getWidth();
816     int height = getHeight();
817
818     jalview.util.ImageMaker im;
819
820     if (type == jalview.util.ImageMaker.TYPE.PNG)
821     {
822       im = new jalview.util.ImageMaker(this,
823               jalview.util.ImageMaker.TYPE.PNG, "Make PNG image from view",
824               width, height, null, null, null, 0, false);
825     }
826     else if (type == jalview.util.ImageMaker.TYPE.EPS)
827     {
828       im = new jalview.util.ImageMaker(this,
829               jalview.util.ImageMaker.TYPE.EPS, "Make EPS file from view",
830               width, height, null, this.getTitle(), null, 0, false);
831     }
832     else
833     {
834
835       im = new jalview.util.ImageMaker(this,
836               jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
837               width, height, null, this.getTitle(), null, 0, false);
838     }
839
840     if (im.getGraphics() != null)
841     {
842       jmb.viewer.renderScreenImage(im.getGraphics(), width, height);
843       im.writeImage();
844     }
845   }
846
847   @Override
848   public void viewerColour_actionPerformed(ActionEvent actionEvent)
849   {
850     if (viewerColour.isSelected())
851     {
852       // disable automatic sequence colouring.
853       jmb.setColourBySequence(false);
854     }
855   }
856
857   @Override
858   public void seqColour_actionPerformed(ActionEvent actionEvent)
859   {
860     jmb.setColourBySequence(seqColour.isSelected());
861     if (_colourwith == null)
862     {
863       _colourwith = new Vector<AlignmentPanel>();
864     }
865     if (jmb.isColourBySequence())
866     {
867       if (!jmb.isLoadingFromArchive())
868       {
869         if (_colourwith.size() == 0 && getAlignmentPanel() != null)
870         {
871           // Make the currently displayed alignment panel the associated view
872           _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
873         }
874       }
875       // Set the colour using the current view for the associated alignframe
876       for (AlignmentPanel ap : _colourwith)
877       {
878         jmb.colourBySequence(ap);
879       }
880     }
881   }
882
883   @Override
884   public void chainColour_actionPerformed(ActionEvent actionEvent)
885   {
886     chainColour.setSelected(true);
887     jmb.colourByChain();
888   }
889
890   @Override
891   public void chargeColour_actionPerformed(ActionEvent actionEvent)
892   {
893     chargeColour.setSelected(true);
894     jmb.colourByCharge();
895   }
896
897   @Override
898   public void zappoColour_actionPerformed(ActionEvent actionEvent)
899   {
900     zappoColour.setSelected(true);
901     jmb.setJalviewColourScheme(new ZappoColourScheme());
902   }
903
904   @Override
905   public void taylorColour_actionPerformed(ActionEvent actionEvent)
906   {
907     taylorColour.setSelected(true);
908     jmb.setJalviewColourScheme(new TaylorColourScheme());
909   }
910
911   @Override
912   public void hydroColour_actionPerformed(ActionEvent actionEvent)
913   {
914     hydroColour.setSelected(true);
915     jmb.setJalviewColourScheme(new HydrophobicColourScheme());
916   }
917
918   @Override
919   public void helixColour_actionPerformed(ActionEvent actionEvent)
920   {
921     helixColour.setSelected(true);
922     jmb.setJalviewColourScheme(new HelixColourScheme());
923   }
924
925   @Override
926   public void strandColour_actionPerformed(ActionEvent actionEvent)
927   {
928     strandColour.setSelected(true);
929     jmb.setJalviewColourScheme(new StrandColourScheme());
930   }
931
932   @Override
933   public void turnColour_actionPerformed(ActionEvent actionEvent)
934   {
935     turnColour.setSelected(true);
936     jmb.setJalviewColourScheme(new TurnColourScheme());
937   }
938
939   @Override
940   public void buriedColour_actionPerformed(ActionEvent actionEvent)
941   {
942     buriedColour.setSelected(true);
943     jmb.setJalviewColourScheme(new BuriedColourScheme());
944   }
945
946   @Override
947   public void purinePyrimidineColour_actionPerformed(ActionEvent actionEvent)
948   {
949     setJalviewColourScheme(new PurinePyrimidineColourScheme());
950   }
951
952   @Override
953   public void userColour_actionPerformed(ActionEvent actionEvent)
954   {
955     userColour.setSelected(true);
956     new UserDefinedColours(this, null);
957   }
958
959   @Override
960   public void backGround_actionPerformed(ActionEvent actionEvent)
961   {
962     java.awt.Color col = JColorChooser
963             .showDialog(this, MessageManager
964                     .getString("label.select_backgroud_colour"), null);
965     if (col != null)
966     {
967       jmb.setBackgroundColour(col);
968     }
969   }
970
971   @Override
972   public void showHelp_actionPerformed(ActionEvent actionEvent)
973   {
974     try
975     {
976       jalview.util.BrowserLauncher
977               .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
978     } catch (Exception ex)
979     {
980     }
981   }
982
983   public void showConsole(boolean showConsole)
984   {
985
986     if (showConsole)
987     {
988       if (splitPane == null)
989       {
990         splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
991         splitPane.setTopComponent(renderPanel);
992         splitPane.setBottomComponent(scriptWindow);
993         this.getContentPane().add(splitPane, BorderLayout.CENTER);
994         splitPane.setDividerLocation(getHeight() - 200);
995         scriptWindow.setVisible(true);
996         scriptWindow.validate();
997         splitPane.validate();
998       }
999
1000     }
1001     else
1002     {
1003       if (splitPane != null)
1004       {
1005         splitPane.setVisible(false);
1006       }
1007
1008       splitPane = null;
1009
1010       this.getContentPane().add(renderPanel, BorderLayout.CENTER);
1011     }
1012
1013     validate();
1014   }
1015
1016   class RenderPanel extends JPanel
1017   {
1018     final Dimension currentSize = new Dimension();
1019
1020     @Override
1021     public void paintComponent(Graphics g)
1022     {
1023       getSize(currentSize);
1024
1025       if (jmb != null && jmb.fileLoadingError != null)
1026       {
1027         g.setColor(Color.black);
1028         g.fillRect(0, 0, currentSize.width, currentSize.height);
1029         g.setColor(Color.white);
1030         g.setFont(new Font("Verdana", Font.BOLD, 14));
1031         g.drawString(MessageManager.getString("label.error_loading_file")
1032                 + "...", 20, currentSize.height / 2);
1033         StringBuffer sb = new StringBuffer();
1034         int lines = 0;
1035         for (int e = 0; e < jmb.getPdbCount(); e++)
1036         {
1037           sb.append(jmb.getPdbEntry(e).getId());
1038           if (e < jmb.getPdbCount() - 1)
1039           {
1040             sb.append(",");
1041           }
1042
1043           if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
1044           {
1045             lines++;
1046             g.drawString(sb.toString(), 20, currentSize.height / 2 - lines
1047                     * g.getFontMetrics().getHeight());
1048           }
1049         }
1050       }
1051       else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
1052       {
1053         g.setColor(Color.black);
1054         g.fillRect(0, 0, currentSize.width, currentSize.height);
1055         g.setColor(Color.white);
1056         g.setFont(new Font("Verdana", Font.BOLD, 14));
1057         g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
1058                 20, currentSize.height / 2);
1059       }
1060       else
1061       {
1062         jmb.viewer.renderScreenImage(g, currentSize.width,
1063                 currentSize.height);
1064       }
1065     }
1066   }
1067
1068   public void updateTitleAndMenus()
1069   {
1070     if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
1071     {
1072       repaint();
1073       return;
1074     }
1075     setChainMenuItems(jmb.chainNames);
1076
1077     this.setTitle(jmb.getViewerTitle());
1078     if (jmb.getPdbFile().length > 1 && jmb.getSequence().length > 1)
1079     {
1080       viewerActionMenu.setVisible(true);
1081     }
1082     if (!jmb.isLoadingFromArchive())
1083     {
1084       seqColour_actionPerformed(null);
1085     }
1086   }
1087
1088   /*
1089    * (non-Javadoc)
1090    * 
1091    * @see
1092    * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
1093    * .ActionEvent)
1094    */
1095   @Override
1096   protected void alignStructs_actionPerformed(ActionEvent actionEvent)
1097   {
1098     alignStructs_withAllAlignPanels();
1099   }
1100
1101   private void alignStructs_withAllAlignPanels()
1102   {
1103     if (getAlignmentPanel() == null)
1104     {
1105       return;
1106     }
1107     ;
1108     if (_alignwith.size() == 0)
1109     {
1110       _alignwith.add(getAlignmentPanel());
1111     }
1112     ;
1113     try
1114     {
1115       AlignmentI[] als = new Alignment[_alignwith.size()];
1116       ColumnSelection[] alc = new ColumnSelection[_alignwith.size()];
1117       int[] alm = new int[_alignwith.size()];
1118       int a = 0;
1119
1120       for (AlignmentPanel ap : _alignwith)
1121       {
1122         als[a] = ap.av.getAlignment();
1123         alm[a] = -1;
1124         alc[a++] = ap.av.getColumnSelection();
1125       }
1126       jmb.superposeStructures(als, alm, alc);
1127     } catch (Exception e)
1128     {
1129       StringBuffer sp = new StringBuffer();
1130       for (AlignmentPanel ap : _alignwith)
1131       {
1132         sp.append("'" + ap.alignFrame.getTitle() + "' ");
1133       }
1134       Cache.log.info("Couldn't align structures with the " + sp.toString()
1135               + "associated alignment panels.", e);
1136
1137     }
1138
1139   }
1140
1141   @Override
1142   public void setJalviewColourScheme(ColourSchemeI ucs)
1143   {
1144     jmb.setJalviewColourScheme(ucs);
1145
1146   }
1147
1148   /**
1149    * 
1150    * @param alignment
1151    * @return first alignment panel displaying given alignment, or the default
1152    *         alignment panel
1153    */
1154   public AlignmentPanel getAlignmentPanelFor(AlignmentI alignment)
1155   {
1156     for (AlignmentPanel ap : getAllAlignmentPanels())
1157     {
1158       if (ap.av.getAlignment() == alignment)
1159       {
1160         return ap;
1161       }
1162     }
1163     return getAlignmentPanel();
1164   }
1165
1166   @Override
1167   public AAStructureBindingModel getBinding()
1168   {
1169     return this.jmb;
1170   }
1171
1172   @Override
1173   public String getStateInfo()
1174   {
1175     return jmb == null ? null : jmb.viewer.getStateInfo();
1176   }
1177
1178   @Override
1179   public ViewerType getViewerType()
1180   {
1181     return ViewerType.JMOL;
1182   }
1183
1184   @Override
1185   protected AAStructureBindingModel getBindingModel()
1186   {
1187     return jmb;
1188   }
1189
1190 }