formatting
[jalview.git] / src / jalview / gui / AppJmol.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  * 
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.gui;
19
20 import java.util.*;
21 import java.awt.*;
22 import javax.swing.*;
23 import javax.swing.event.*;
24
25 import java.awt.event.*;
26 import java.io.*;
27
28 import jalview.jbgui.GStructureViewer;
29 import jalview.api.AlignmentViewPanel;
30 import jalview.api.SequenceStructureBinding;
31 import jalview.bin.Cache;
32 import jalview.datamodel.*;
33 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
34 import jalview.structure.*;
35 import jalview.datamodel.PDBEntry;
36 import jalview.io.*;
37 import jalview.schemes.*;
38 import jalview.util.Platform;
39
40 public class AppJmol extends GStructureViewer implements Runnable,
41         SequenceStructureBinding, ViewSetProvider
42
43 {
44   AppJmolBinding jmb;
45
46   JPanel scriptWindow;
47
48   JSplitPane splitPane;
49
50   RenderPanel renderPanel;
51
52   AlignmentPanel ap;
53
54   Vector atomsPicked = new Vector();
55
56   private boolean addingStructures = false;
57
58   /**
59    * 
60    * @param file
61    * @param id
62    * @param seq
63    * @param ap
64    * @param loadStatus
65    * @param bounds
66    * @deprecated defaults to AppJmol(String[] files, ... , viewid);
67    */
68   public AppJmol(String file, String id, SequenceI[] seq,
69           AlignmentPanel ap, String loadStatus, Rectangle bounds)
70   {
71     this(file, id, seq, ap, loadStatus, bounds, null);
72   }
73
74   /**
75    * @deprecated
76    */
77   public AppJmol(String file, String id, SequenceI[] seq,
78           AlignmentPanel ap, String loadStatus, Rectangle bounds,
79           String viewid)
80   {
81     this(new String[]
82     { file }, new String[]
83     { id }, new SequenceI[][]
84     { seq }, ap, true, true, false, loadStatus, bounds, viewid);
85   }
86
87   ViewSelectionMenu seqColourBy;
88
89   /**
90    * 
91    * @param files
92    * @param ids
93    * @param seqs
94    * @param ap
95    * @param usetoColour
96    *          - add the alignment panel to the list used for colouring these
97    *          structures
98    * @param useToAlign
99    *          - add the alignment panel to the list used for aligning these
100    *          structures
101    * @param leaveColouringToJmol
102    *          - do not update the colours from any other source. Jmol is
103    *          handling them
104    * @param loadStatus
105    * @param bounds
106    * @param viewid
107    */
108   public AppJmol(String[] files, String[] ids, SequenceI[][] seqs,
109           AlignmentPanel ap, boolean usetoColour, boolean useToAlign,
110           boolean leaveColouringToJmol, String loadStatus,
111           Rectangle bounds, String viewid)
112   {
113     PDBEntry[] pdbentrys = new PDBEntry[files.length];
114     for (int i = 0; i < pdbentrys.length; i++)
115     {
116       PDBEntry pdbentry = new PDBEntry();
117       pdbentry.setFile(files[i]);
118       pdbentry.setId(ids[i]);
119       pdbentrys[i] = pdbentry;
120     }
121     // / TODO: check if protocol is needed to be set, and if chains are
122     // autodiscovered.
123     jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
124             pdbentrys, seqs, null, null);
125
126     jmb.setLoadingFromArchive(true);
127     addAlignmentPanel(ap);
128     if (useToAlign)
129     {
130       useAlignmentPanelForSuperposition(ap);
131     }
132     if (leaveColouringToJmol || !usetoColour)
133     {
134       jmb.setColourBySequence(false);
135       seqColour.setSelected(false);
136       jmolColour.setSelected(true);
137     }
138     if (usetoColour)
139     {
140       useAlignmentPanelForColourbyseq(ap);
141       jmb.setColourBySequence(true);
142       seqColour.setSelected(true);
143       jmolColour.setSelected(false);
144     }
145     this.setBounds(bounds);
146     initMenus();
147     viewId = viewid;
148     // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
149     // bounds.width,bounds.height);
150
151     this.addInternalFrameListener(new InternalFrameAdapter()
152     {
153       public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
154       {
155         closeViewer();
156       }
157     });
158     initJmol(loadStatus); // pdbentry, seq, JBPCHECK!
159
160   }
161
162   private void initMenus()
163   {
164     seqColour.setSelected(jmb.isColourBySequence());
165     jmolColour.setSelected(!jmb.isColourBySequence());
166     if (_colourwith == null)
167     {
168       _colourwith = new Vector<AlignmentPanel>();
169     }
170     if (_alignwith == null)
171     {
172       _alignwith = new Vector<AlignmentPanel>();
173     }
174
175     seqColourBy = new ViewSelectionMenu("Colour by ..", this, _colourwith,
176             new ItemListener()
177             {
178
179               @Override
180               public void itemStateChanged(ItemEvent e)
181               {
182                 if (!seqColour.isSelected())
183                 {
184                   seqColour.doClick();
185                 }
186                 else
187                 {
188                   // update the jmol display now.
189                   seqColour_actionPerformed(null);
190                 }
191               }
192             });
193     viewMenu.add(seqColourBy);
194     final ItemListener handler;
195     JMenu alpanels = new ViewSelectionMenu("Superpose with ..", this,
196             _alignwith, handler = new ItemListener()
197             {
198
199               @Override
200               public void itemStateChanged(ItemEvent e)
201               {
202                 alignStructs.setEnabled(_alignwith.size() > 0);
203                 alignStructs.setToolTipText("Align structures using "
204                         + _alignwith.size() + " linked alignment views");
205               }
206             });
207     handler.itemStateChanged(null);
208     jmolActionMenu.add(alpanels);
209     jmolActionMenu.addMenuListener(new MenuListener()
210     {
211
212       @Override
213       public void menuSelected(MenuEvent e)
214       {
215         handler.itemStateChanged(null);
216       }
217
218       @Override
219       public void menuDeselected(MenuEvent e)
220       {
221         // TODO Auto-generated method stub
222
223       }
224
225       @Override
226       public void menuCanceled(MenuEvent e)
227       {
228         // TODO Auto-generated method stub
229
230       }
231     });
232   }
233
234   IProgressIndicator progressBar = null;
235
236   /**
237    * add a single PDB structure to a new or existing Jmol view
238    * 
239    * @param pdbentry
240    * @param seq
241    * @param chains
242    * @param ap
243    */
244   public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
245           final AlignmentPanel ap)
246   {
247     progressBar = ap.alignFrame;
248     // ////////////////////////////////
249     // Is the pdb file already loaded?
250     String alreadyMapped = ap.getStructureSelectionManager()
251             .alreadyMappedToFile(pdbentry.getId());
252
253     if (alreadyMapped != null)
254     {
255       int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
256               pdbentry.getId() + " is already displayed."
257                       + "\nDo you want to re-use this viewer ?",
258               "Map Sequences to Visible Window: " + pdbentry.getId(),
259               JOptionPane.YES_NO_OPTION);
260
261       if (option == JOptionPane.YES_OPTION)
262       {
263         // TODO : Fix multiple seq to one chain issue here.
264         ap.getStructureSelectionManager().setMapping(seq, chains,
265                 alreadyMapped, AppletFormatAdapter.FILE);
266         if (ap.seqPanel.seqCanvas.fr != null)
267         {
268           ap.seqPanel.seqCanvas.fr.featuresAdded();
269           ap.paintAlignment(true);
270         }
271
272         // Now this AppJmol is mapped to new sequences. We must add them to
273         // the exisiting array
274         JInternalFrame[] frames = Desktop.instance.getAllFrames();
275
276         for (int i = 0; i < frames.length; i++)
277         {
278           if (frames[i] instanceof AppJmol)
279           {
280             final AppJmol topJmol = ((AppJmol) frames[i]);
281             // JBPNOTE: this looks like a binding routine, rather than a gui
282             // routine
283             for (int pe = 0; pe < topJmol.jmb.pdbentry.length; pe++)
284             {
285               if (topJmol.jmb.pdbentry[pe].getFile().equals(alreadyMapped))
286               {
287                 topJmol.jmb.addSequence(pe, seq);
288                 topJmol.addAlignmentPanel(ap);
289                 // add it to the set used for colouring
290                 topJmol.useAlignmentPanelForColourbyseq(ap);
291                 topJmol.buildJmolActionMenu();
292                 ap.getStructureSelectionManager()
293                         .sequenceColoursChanged(ap);
294                 break;
295               }
296             }
297           }
298         }
299
300         return;
301       }
302     }
303     // /////////////////////////////////
304     // Check if there are other Jmol views involving this alignment
305     // and prompt user about adding this molecule to one of them
306     Vector existingViews = getJmolsFor(ap);
307     if (existingViews.size() > 0)
308     {
309       Enumeration jm = existingViews.elements();
310       while (jm.hasMoreElements())
311       {
312         AppJmol topJmol = (AppJmol) jm.nextElement();
313         // TODO: highlight topJmol in view somehow
314         int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
315                 "Do you want to add " + pdbentry.getId()
316                         + " to the view called\n'" + topJmol.getTitle()
317                         + "'\n", "Align to existing structure view",
318                 JOptionPane.YES_NO_OPTION);
319         if (option == JOptionPane.YES_OPTION)
320         {
321           topJmol.useAlignmentPanelForSuperposition(ap);
322           topJmol.addStructure(pdbentry, seq, chains, true, ap.alignFrame);
323           return;
324         }
325       }
326     }
327     // /////////////////////////////////
328     openNewJmol(ap, new PDBEntry[]
329     { pdbentry }, new SequenceI[][]
330     { seq });
331   }
332
333   private void openNewJmol(AlignmentPanel ap, PDBEntry[] pdbentrys,
334           SequenceI[][] seqs)
335   {
336     progressBar = ap.alignFrame;
337     jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
338             pdbentrys, seqs, null, null);
339     addAlignmentPanel(ap);
340     useAlignmentPanelForColourbyseq(ap);
341     if (pdbentrys.length > 1)
342     {
343       alignAddedStructures = true;
344       useAlignmentPanelForSuperposition(ap);
345     }
346     jmb.setColourBySequence(true);
347     setSize(400, 400); // probably should be a configurable/dynamic default here
348     initMenus();
349     worker = null;
350     {
351       addingStructures = false;
352       worker = new Thread(this);
353       worker.start();
354     }
355     this.addInternalFrameListener(new InternalFrameAdapter()
356     {
357       public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
358       {
359         closeViewer();
360       }
361     });
362
363   }
364
365   /**
366    * create a new Jmol containing several structures superimposed using the
367    * given alignPanel.
368    * 
369    * @param ap
370    * @param pe
371    * @param seqs
372    */
373   public AppJmol(AlignmentPanel ap, PDBEntry[] pe, SequenceI[][] seqs)
374   {
375     openNewJmol(ap, pe, seqs);
376   }
377
378   /**
379    * list of sequenceSet ids associated with the view
380    */
381   ArrayList<String> _aps = new ArrayList();
382
383   public AlignmentPanel[] getAllAlignmentPanels()
384   {
385     AlignmentPanel[] t, list = new AlignmentPanel[0];
386     for (String setid : _aps)
387     {
388       AlignmentPanel[] panels = PaintRefresher.getAssociatedPanels(setid);
389       if (panels != null)
390       {
391         t = new AlignmentPanel[list.length + panels.length];
392         System.arraycopy(list, 0, t, 0, list.length);
393         System.arraycopy(panels, 0, t, list.length, panels.length);
394         list = t;
395       }
396     }
397
398     return list;
399   }
400
401   /**
402    * list of alignment panels to use for superposition
403    */
404   Vector<AlignmentPanel> _alignwith = new Vector<AlignmentPanel>();
405
406   /**
407    * list of alignment panels that are used for colouring structures by aligned
408    * sequences
409    */
410   Vector<AlignmentPanel> _colourwith = new Vector<AlignmentPanel>();
411
412   /**
413    * set the primary alignmentPanel reference and add another alignPanel to the
414    * list of ones to use for colouring and aligning
415    * 
416    * @param nap
417    */
418   public void addAlignmentPanel(AlignmentPanel nap)
419   {
420     if (ap == null)
421     {
422       ap = nap;
423     }
424     if (!_aps.contains(nap.av.getSequenceSetId()))
425     {
426       _aps.add(nap.av.getSequenceSetId());
427     }
428   }
429
430   /**
431    * remove any references held to the given alignment panel
432    * 
433    * @param nap
434    */
435   public void removeAlignmentPanel(AlignmentPanel nap)
436   {
437     try
438     {
439       _alignwith.remove(nap);
440       _colourwith.remove(nap);
441       if (ap == nap)
442       {
443         ap = null;
444         for (AlignmentPanel aps : getAllAlignmentPanels())
445         {
446           if (aps != nap)
447           {
448             ap = aps;
449             break;
450           }
451         }
452       }
453     } catch (Exception ex)
454     {
455     }
456     if (ap != null)
457     {
458       buildJmolActionMenu();
459     }
460   }
461
462   public void useAlignmentPanelForSuperposition(AlignmentPanel nap)
463   {
464     addAlignmentPanel(nap);
465     if (!_alignwith.contains(nap))
466     {
467       _alignwith.add(nap);
468     }
469   }
470
471   public void excludeAlignmentPanelForSuperposition(AlignmentPanel nap)
472   {
473     if (_alignwith.contains(nap))
474     {
475       _alignwith.remove(nap);
476     }
477   }
478
479   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap,
480           boolean enableColourBySeq)
481   {
482     useAlignmentPanelForColourbyseq(nap);
483     jmb.setColourBySequence(enableColourBySeq);
484     seqColour.setSelected(enableColourBySeq);
485     jmolColour.setSelected(!enableColourBySeq);
486   }
487
488   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap)
489   {
490     addAlignmentPanel(nap);
491     if (!_colourwith.contains(nap))
492     {
493       _colourwith.add(nap);
494     }
495   }
496
497   public void excludeAlignmentPanelForColourbyseq(AlignmentPanel nap)
498   {
499     if (_colourwith.contains(nap))
500     {
501       _colourwith.remove(nap);
502     }
503   }
504
505   /**
506    * pdb retrieval thread.
507    */
508   private Thread worker = null;
509
510   /**
511    * add a new structure (with associated sequences and chains) to this viewer,
512    * retrieving it if necessary first.
513    * 
514    * @param pdbentry
515    * @param seq
516    * @param chains
517    * @param alignFrame
518    * @param align
519    *          if true, new structure(s) will be align using associated alignment
520    */
521   private void addStructure(final PDBEntry pdbentry, final SequenceI[] seq,
522           final String[] chains, final boolean b,
523           final IProgressIndicator alignFrame)
524   {
525     if (pdbentry.getFile() == null)
526     {
527       if (worker != null && worker.isAlive())
528       {
529         // a retrieval is in progress, wait around and add ourselves to the
530         // queue.
531         new Thread(new Runnable()
532         {
533           public void run()
534           {
535             while (worker != null && worker.isAlive() && _started)
536             {
537               try
538               {
539                 Thread.sleep(100 + ((int) Math.random() * 100));
540
541               } catch (Exception e)
542               {
543               }
544
545             }
546             // and call ourselves again.
547             addStructure(pdbentry, seq, chains, b, alignFrame);
548           }
549         }).start();
550         return;
551       }
552     }
553     // otherwise, start adding the structure.
554     jmb.addSequenceAndChain(new PDBEntry[]
555     { pdbentry }, new SequenceI[][]
556     { seq }, new String[][]
557     { chains });
558     addingStructures = true;
559     _started = false;
560     alignAddedStructures = b;
561     progressBar = alignFrame; // visual indication happens on caller frame.
562     (worker = new Thread(this)).start();
563     return;
564   }
565
566   private Vector getJmolsFor(AlignmentPanel ap2)
567   {
568     Vector otherJmols = new Vector();
569     // Now this AppJmol is mapped to new sequences. We must add them to
570     // the exisiting array
571     JInternalFrame[] frames = Desktop.instance.getAllFrames();
572
573     for (int i = 0; i < frames.length; i++)
574     {
575       if (frames[i] instanceof AppJmol)
576       {
577         AppJmol topJmol = ((AppJmol) frames[i]);
578         if (topJmol.isLinkedWith(ap2))
579         {
580           otherJmols.addElement(topJmol);
581         }
582       }
583     }
584     return otherJmols;
585   }
586
587   void initJmol(String command)
588   {
589     jmb.setFinishedInit(false);
590     renderPanel = new RenderPanel();
591     // TODO: consider waiting until the structure/view is fully loaded before
592     // displaying
593     this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
594     jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
595             getBounds().width, getBounds().height);
596     if (scriptWindow == null)
597     {
598       BorderLayout bl = new BorderLayout();
599       bl.setHgap(0);
600       bl.setVgap(0);
601       scriptWindow = new JPanel(bl);
602       scriptWindow.setVisible(false);
603     }
604     ;
605     jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
606             null);
607     jmb.newJmolPopup(true, "Jmol", true);
608     if (command == null)
609     {
610       command = "";
611     }
612     jmb.evalStateCommand(command);
613     jmb.setFinishedInit(true);
614   }
615
616   void setChainMenuItems(Vector chains)
617   {
618     chainMenu.removeAll();
619     if (chains == null)
620     {
621       return;
622     }
623     JMenuItem menuItem = new JMenuItem("All");
624     menuItem.addActionListener(new ActionListener()
625     {
626       public void actionPerformed(ActionEvent evt)
627       {
628         allChainsSelected = true;
629         for (int i = 0; i < chainMenu.getItemCount(); i++)
630         {
631           if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
632             ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
633         }
634         centerViewer();
635         allChainsSelected = false;
636       }
637     });
638
639     chainMenu.add(menuItem);
640
641     for (int c = 0; c < chains.size(); c++)
642     {
643       menuItem = new JCheckBoxMenuItem(chains.elementAt(c).toString(), true);
644       menuItem.addItemListener(new ItemListener()
645       {
646         public void itemStateChanged(ItemEvent evt)
647         {
648           if (!allChainsSelected)
649             centerViewer();
650         }
651       });
652
653       chainMenu.add(menuItem);
654     }
655   }
656
657   boolean allChainsSelected = false;
658
659   private boolean alignAddedStructures = false;
660
661   void centerViewer()
662   {
663     Vector toshow = new Vector();
664     String lbl;
665     int mlength, p, mnum;
666     for (int i = 0; i < chainMenu.getItemCount(); i++)
667     {
668       if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
669       {
670         JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
671         if (item.isSelected())
672         {
673           toshow.addElement(item.getText());
674         }
675       }
676     }
677     jmb.centerViewer(toshow);
678   }
679
680   void closeViewer()
681   {
682     jmb.closeViewer();
683     ap = null;
684     _aps.clear();
685     _alignwith.clear();
686     _colourwith.clear();
687     // TODO: check for memory leaks where instance isn't finalised because jmb
688     // holds a reference to the window
689     jmb = null;
690   }
691
692   /**
693    * state flag for PDB retrieval thread
694    */
695   private boolean _started = false;
696
697   public void run()
698   {
699     _started = true;
700     String pdbid = "";
701     // todo - record which pdbids were successfuly imported.
702     StringBuffer errormsgs = new StringBuffer(), files = new StringBuffer();
703     try
704     {
705       String[] curfiles = jmb.getPdbFile(); // files currently in viewer
706       // TODO: replace with reference fetching/transfer code (validate PDBentry
707       // as a DBRef?)
708       jalview.ws.dbsources.Pdb pdbclient = new jalview.ws.dbsources.Pdb();
709       for (int pi = 0; pi < jmb.pdbentry.length; pi++)
710       {
711         String file = jmb.pdbentry[pi].getFile();
712         if (file == null)
713         {
714           // retrieve the pdb and store it locally
715           AlignmentI pdbseq = null;
716           pdbid = jmb.pdbentry[pi].getId();
717           long hdl = pdbid.hashCode() - System.currentTimeMillis();
718           if (progressBar != null)
719           {
720             progressBar.setProgressBar("Fetching PDB " + pdbid, hdl);
721           }
722           try
723           {
724             pdbseq = pdbclient.getSequenceRecords(pdbid = jmb.pdbentry[pi]
725                     .getId());
726           } catch (OutOfMemoryError oomerror)
727           {
728             new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
729           } catch (Exception ex)
730           {
731             ex.printStackTrace();
732             errormsgs.append("'" + pdbid + "'");
733           }
734           if (progressBar != null)
735           {
736             progressBar.setProgressBar("Finished.", hdl);
737           }
738           if (pdbseq != null)
739           {
740             // just transfer the file name from the first sequence's first
741             // PDBEntry
742             file = new File(((PDBEntry) pdbseq.getSequenceAt(0).getPDBId()
743                     .elementAt(0)).getFile()).getAbsolutePath();
744             jmb.pdbentry[pi].setFile(file);
745
746             files.append(" \"" + Platform.escapeString(file) + "\"");
747           }
748           else
749           {
750             errormsgs.append("'" + pdbid + "' ");
751           }
752         }
753         else
754         {
755           if (curfiles != null && curfiles.length > 0)
756           {
757             addingStructures = true; // already files loaded.
758             for (int c = 0; c < curfiles.length; c++)
759             {
760               if (curfiles[c].equals(file))
761               {
762                 file = null;
763                 break;
764               }
765             }
766           }
767           if (file != null)
768           {
769             files.append(" \"" + Platform.escapeString(file) + "\"");
770           }
771         }
772       }
773     } catch (OutOfMemoryError oomerror)
774     {
775       new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
776     } catch (Exception ex)
777     {
778       ex.printStackTrace();
779       errormsgs.append("When retrieving pdbfiles : current was: '" + pdbid
780               + "'");
781     }
782     if (errormsgs.length() > 0)
783     {
784
785       JOptionPane.showInternalMessageDialog(Desktop.desktop,
786               "The following pdb entries could not be retrieved from the PDB:\n"
787                       + errormsgs.toString()
788                       + "\nPlease try downloading them manually.",
789               "Couldn't load file", JOptionPane.ERROR_MESSAGE);
790
791     }
792     long lastnotify = jmb.getLoadNotifiesHandled();
793     if (files.length() > 0)
794     {
795       if (!addingStructures)
796       {
797
798         try
799         {
800           initJmol("load FILES " + files.toString());
801         } catch (OutOfMemoryError oomerror)
802         {
803           new OOMWarning("When trying to open the Jmol viewer!", oomerror);
804           Cache.log.debug("File locations are " + files);
805         } catch (Exception ex)
806         {
807           Cache.log.error("Couldn't open Jmol viewer!", ex);
808         }
809       }
810       else
811       {
812         StringBuffer cmd = new StringBuffer();
813         cmd.append("loadingJalviewdata=true\nload APPEND ");
814         cmd.append(files.toString());
815         cmd.append("\nloadingJalviewdata=null");
816         final String command = cmd.toString();
817         cmd = null;
818         lastnotify = jmb.getLoadNotifiesHandled();
819
820         try
821         {
822           jmb.evalStateCommand(command);
823         } catch (OutOfMemoryError oomerror)
824         {
825           new OOMWarning(
826                   "When trying to add structures to the Jmol viewer!",
827                   oomerror);
828           Cache.log.debug("File locations are " + files);
829         } catch (Exception ex)
830         {
831           Cache.log.error("Couldn't add files to Jmol viewer!", ex);
832         }
833       }
834
835       // need to wait around until script has finished
836       while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
837               : (jmb.isFinishedInit() && jmb.getPdbFile().length != jmb.pdbentry.length))
838       {
839         try
840         {
841           Cache.log.debug("Waiting around for jmb notify.");
842           Thread.sleep(35);
843         } catch (Exception e)
844         {
845         }
846       }
847       // refresh the sequence colours for the new structure(s)
848       for (AlignmentPanel ap : _colourwith)
849       {
850         jmb.updateColours(ap);
851       }
852       // do superposition if asked to
853       if (alignAddedStructures)
854       {
855         javax.swing.SwingUtilities.invokeLater(new Runnable()
856         {
857           public void run()
858           {
859             alignStructs_withAllAlignPanels();
860             // jmb.superposeStructures(ap.av.getAlignment(), -1, null);
861           }
862         });
863         alignAddedStructures = false;
864       }
865       addingStructures = false;
866
867     }
868     _started = false;
869     worker = null;
870   }
871
872   public void pdbFile_actionPerformed(ActionEvent actionEvent)
873   {
874     JalviewFileChooser chooser = new JalviewFileChooser(
875             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
876
877     chooser.setFileView(new JalviewFileView());
878     chooser.setDialogTitle("Save PDB File");
879     chooser.setToolTipText("Save");
880
881     int value = chooser.showSaveDialog(this);
882
883     if (value == JalviewFileChooser.APPROVE_OPTION)
884     {
885       try
886       {
887         // TODO: cope with multiple PDB files in view
888         BufferedReader in = new BufferedReader(new FileReader(
889                 jmb.getPdbFile()[0]));
890         File outFile = chooser.getSelectedFile();
891
892         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
893         String data;
894         while ((data = in.readLine()) != null)
895         {
896           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
897           {
898             out.println(data);
899           }
900         }
901         out.close();
902       } catch (Exception ex)
903       {
904         ex.printStackTrace();
905       }
906     }
907   }
908
909   public void viewMapping_actionPerformed(ActionEvent actionEvent)
910   {
911     jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
912     try
913     {
914       for (int pdbe = 0; pdbe < jmb.pdbentry.length; pdbe++)
915       {
916         cap.appendText(jmb.printMapping(jmb.pdbentry[pdbe].getFile()));
917         cap.appendText("\n");
918       }
919     } catch (OutOfMemoryError e)
920     {
921       new OOMWarning(
922               "composing sequence-structure alignments for display in text box.",
923               e);
924       cap.dispose();
925       return;
926     }
927     jalview.gui.Desktop.addInternalFrame(cap, "PDB - Sequence Mapping",
928             550, 600);
929   }
930
931   /**
932    * DOCUMENT ME!
933    * 
934    * @param e
935    *          DOCUMENT ME!
936    */
937   public void eps_actionPerformed(ActionEvent e)
938   {
939     makePDBImage(jalview.util.ImageMaker.EPS);
940   }
941
942   /**
943    * DOCUMENT ME!
944    * 
945    * @param e
946    *          DOCUMENT ME!
947    */
948   public void png_actionPerformed(ActionEvent e)
949   {
950     makePDBImage(jalview.util.ImageMaker.PNG);
951   }
952
953   void makePDBImage(int type)
954   {
955     int width = getWidth();
956     int height = getHeight();
957
958     jalview.util.ImageMaker im;
959
960     if (type == jalview.util.ImageMaker.PNG)
961     {
962       im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.PNG,
963               "Make PNG image from view", width, height, null, null);
964     }
965     else
966     {
967       im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.EPS,
968               "Make EPS file from view", width, height, null,
969               this.getTitle());
970     }
971
972     if (im.getGraphics() != null)
973     {
974       Rectangle rect = new Rectangle(width, height);
975       jmb.viewer.renderScreenImage(im.getGraphics(), rect.getSize(), rect);
976       im.writeImage();
977     }
978   }
979
980   public void jmolColour_actionPerformed(ActionEvent actionEvent)
981   {
982     if (jmolColour.isSelected())
983     {
984       // disable automatic sequence colouring.
985       jmb.setColourBySequence(false);
986     }
987   }
988
989   public void seqColour_actionPerformed(ActionEvent actionEvent)
990   {
991     jmb.setColourBySequence(seqColour.isSelected());
992     if (_colourwith == null)
993     {
994       _colourwith = new Vector<AlignmentPanel>();
995     }
996     if (jmb.isColourBySequence())
997     {
998       if (!jmb.isLoadingFromArchive())
999       {
1000         if (_colourwith.size() == 0 && ap != null)
1001         {
1002           // Make the currently displayed alignment panel the associated view
1003           _colourwith.add(ap.alignFrame.alignPanel);
1004         }
1005       }
1006       // Set the colour using the current view for the associated alignframe
1007       for (AlignmentPanel ap : _colourwith)
1008       {
1009         jmb.colourBySequence(ap.av.showSequenceFeatures, ap);
1010       }
1011     }
1012   }
1013
1014   public void chainColour_actionPerformed(ActionEvent actionEvent)
1015   {
1016     chainColour.setSelected(true);
1017     jmb.colourByChain();
1018   }
1019
1020   public void chargeColour_actionPerformed(ActionEvent actionEvent)
1021   {
1022     chargeColour.setSelected(true);
1023     jmb.colourByCharge();
1024   }
1025
1026   public void zappoColour_actionPerformed(ActionEvent actionEvent)
1027   {
1028     zappoColour.setSelected(true);
1029     jmb.setJalviewColourScheme(new ZappoColourScheme());
1030   }
1031
1032   public void taylorColour_actionPerformed(ActionEvent actionEvent)
1033   {
1034     taylorColour.setSelected(true);
1035     jmb.setJalviewColourScheme(new TaylorColourScheme());
1036   }
1037
1038   public void hydroColour_actionPerformed(ActionEvent actionEvent)
1039   {
1040     hydroColour.setSelected(true);
1041     jmb.setJalviewColourScheme(new HydrophobicColourScheme());
1042   }
1043
1044   public void helixColour_actionPerformed(ActionEvent actionEvent)
1045   {
1046     helixColour.setSelected(true);
1047     jmb.setJalviewColourScheme(new HelixColourScheme());
1048   }
1049
1050   public void strandColour_actionPerformed(ActionEvent actionEvent)
1051   {
1052     strandColour.setSelected(true);
1053     jmb.setJalviewColourScheme(new StrandColourScheme());
1054   }
1055
1056   public void turnColour_actionPerformed(ActionEvent actionEvent)
1057   {
1058     turnColour.setSelected(true);
1059     jmb.setJalviewColourScheme(new TurnColourScheme());
1060   }
1061
1062   public void buriedColour_actionPerformed(ActionEvent actionEvent)
1063   {
1064     buriedColour.setSelected(true);
1065     jmb.setJalviewColourScheme(new BuriedColourScheme());
1066   }
1067
1068   public void purinePyrimidineColour_actionPerformed(ActionEvent actionEvent)
1069   {
1070     setJalviewColourScheme(new PurinePyrimidineColourScheme());
1071   }
1072
1073   public void userColour_actionPerformed(ActionEvent actionEvent)
1074   {
1075     userColour.setSelected(true);
1076     new UserDefinedColours(this, null);
1077   }
1078
1079   public void backGround_actionPerformed(ActionEvent actionEvent)
1080   {
1081     java.awt.Color col = JColorChooser.showDialog(this,
1082             "Select Background Colour", null);
1083     if (col != null)
1084     {
1085       jmb.setBackgroundColour(col);
1086     }
1087   }
1088
1089   public void jmolHelp_actionPerformed(ActionEvent actionEvent)
1090   {
1091     try
1092     {
1093       jalview.util.BrowserLauncher
1094               .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
1095     } catch (Exception ex)
1096     {
1097     }
1098   }
1099
1100   public void showConsole(boolean showConsole)
1101   {
1102
1103     if (showConsole)
1104     {
1105       if (splitPane == null)
1106       {
1107         splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
1108         splitPane.setTopComponent(renderPanel);
1109         splitPane.setBottomComponent(scriptWindow);
1110         this.getContentPane().add(splitPane, BorderLayout.CENTER);
1111         splitPane.setDividerLocation(getHeight() - 200);
1112         scriptWindow.setVisible(true);
1113         scriptWindow.validate();
1114         splitPane.validate();
1115       }
1116
1117     }
1118     else
1119     {
1120       if (splitPane != null)
1121       {
1122         splitPane.setVisible(false);
1123       }
1124
1125       splitPane = null;
1126
1127       this.getContentPane().add(renderPanel, BorderLayout.CENTER);
1128     }
1129
1130     validate();
1131   }
1132
1133   class RenderPanel extends JPanel
1134   {
1135     final Dimension currentSize = new Dimension();
1136
1137     final Rectangle rectClip = new Rectangle();
1138
1139     public void paintComponent(Graphics g)
1140     {
1141       getSize(currentSize);
1142       g.getClipBounds(rectClip);
1143
1144       if (jmb.fileLoadingError != null)
1145       {
1146         g.setColor(Color.black);
1147         g.fillRect(0, 0, currentSize.width, currentSize.height);
1148         g.setColor(Color.white);
1149         g.setFont(new Font("Verdana", Font.BOLD, 14));
1150         g.drawString("Error loading file...", 20, currentSize.height / 2);
1151         StringBuffer sb = new StringBuffer();
1152         int lines = 0;
1153         for (int e = 0; e < jmb.pdbentry.length; e++)
1154         {
1155           sb.append(jmb.pdbentry[e].getId());
1156           if (e < jmb.pdbentry.length - 1)
1157           {
1158             sb.append(",");
1159           }
1160
1161           if (e == jmb.pdbentry.length - 1 || sb.length() > 20)
1162           {
1163             lines++;
1164             g.drawString(sb.toString(), 20, currentSize.height / 2 - lines
1165                     * g.getFontMetrics().getHeight());
1166           }
1167         }
1168       }
1169       else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
1170       {
1171         g.setColor(Color.black);
1172         g.fillRect(0, 0, currentSize.width, currentSize.height);
1173         g.setColor(Color.white);
1174         g.setFont(new Font("Verdana", Font.BOLD, 14));
1175         g.drawString("Retrieving PDB data....", 20, currentSize.height / 2);
1176       }
1177       else
1178       {
1179         jmb.viewer.renderScreenImage(g, currentSize, rectClip);
1180       }
1181     }
1182   }
1183
1184   String viewId = null;
1185
1186   public String getViewId()
1187   {
1188     if (viewId == null)
1189     {
1190       viewId = System.currentTimeMillis() + "." + this.hashCode();
1191     }
1192     return viewId;
1193   }
1194
1195   public void updateTitleAndMenus()
1196   {
1197     if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
1198     {
1199       repaint();
1200       return;
1201     }
1202     setChainMenuItems(jmb.chainNames);
1203
1204     this.setTitle(jmb.getViewerTitle());
1205     if (jmb.getPdbFile().length > 1 && jmb.sequence.length > 1)
1206     {
1207       jmolActionMenu.setVisible(true);
1208     }
1209     if (!jmb.isLoadingFromArchive())
1210     {
1211       seqColour_actionPerformed(null);
1212     }
1213   }
1214
1215   protected void buildJmolActionMenu()
1216   {
1217     if (_alignwith == null)
1218     {
1219       _alignwith = new Vector<AlignmentPanel>();
1220     }
1221     if (_alignwith.size() == 0 && ap != null)
1222     {
1223       _alignwith.add(ap);
1224     }
1225     ;
1226     for (Component c : jmolActionMenu.getMenuComponents())
1227     {
1228       if (c != alignStructs)
1229       {
1230         jmolActionMenu.remove((JMenuItem) c);
1231       }
1232     }
1233     final ItemListener handler;
1234   }
1235
1236   /*
1237    * (non-Javadoc)
1238    * 
1239    * @see
1240    * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
1241    * .ActionEvent)
1242    */
1243   @Override
1244   protected void alignStructs_actionPerformed(ActionEvent actionEvent)
1245   {
1246     alignStructs_withAllAlignPanels();
1247   }
1248
1249   private void alignStructs_withAllAlignPanels()
1250   {
1251     if (ap == null)
1252     {
1253       return;
1254     }
1255     ;
1256     if (_alignwith.size() == 0)
1257     {
1258       _alignwith.add(ap);
1259     }
1260     ;
1261     try
1262     {
1263       AlignmentI[] als = new Alignment[_alignwith.size()];
1264       ColumnSelection[] alc = new ColumnSelection[_alignwith.size()];
1265       int[] alm = new int[_alignwith.size()];
1266       int a = 0;
1267
1268       for (AlignmentPanel ap : _alignwith)
1269       {
1270         als[a] = ap.av.getAlignment();
1271         alm[a] = -1;
1272         alc[a++] = ap.av.getColumnSelection();
1273       }
1274       jmb.superposeStructures(als, alm, alc);
1275     } catch (Exception e)
1276     {
1277       StringBuffer sp = new StringBuffer();
1278       for (AlignmentPanel ap : _alignwith)
1279       {
1280         sp.append("'" + ap.alignFrame.getTitle() + "' ");
1281       }
1282       Cache.log.info("Couldn't align structures with the " + sp.toString()
1283               + "associated alignment panels.", e);
1284
1285     }
1286
1287   }
1288
1289   public void setJalviewColourScheme(ColourSchemeI ucs)
1290   {
1291     jmb.setJalviewColourScheme(ucs);
1292
1293   }
1294
1295   /**
1296    * 
1297    * @param alignment
1298    * @return first alignment panel displaying given alignment, or the default
1299    *         alignment panel
1300    */
1301   public AlignmentPanel getAlignmentPanelFor(AlignmentI alignment)
1302   {
1303     for (AlignmentPanel ap : getAllAlignmentPanels())
1304     {
1305       if (ap.av.getAlignment() == alignment)
1306       {
1307         return ap;
1308       }
1309     }
1310     return ap;
1311   }
1312
1313   /**
1314    * 
1315    * @param ap2
1316    * @return true if this Jmol instance is linked with the given alignPanel
1317    */
1318   public boolean isLinkedWith(AlignmentPanel ap2)
1319   {
1320     return _aps.contains(ap2.av.getSequenceSetId());
1321   }
1322
1323   public boolean isUsedforaligment(AlignmentPanel ap2)
1324   {
1325
1326     return (_alignwith != null) && _alignwith.contains(ap2);
1327   }
1328
1329   public boolean isUsedforcolourby(AlignmentPanel ap2)
1330   {
1331     return (_colourwith != null) && _colourwith.contains(ap2);
1332   }
1333
1334   /**
1335    * 
1336    * @return TRUE if the view is NOT being coloured by sequence associations.
1337    */
1338   public boolean isColouredByJmol()
1339   {
1340     return !jmb.isColourBySequence();
1341   }
1342
1343 }