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