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