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