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