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