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