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