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