JAL-1333 more abstraction and refactoring and working demo of Jalview talking to...
[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("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("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);
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 = new File(jmb.pdbentry[pi].getFile())
693                 .getAbsoluteFile().getPath();
694         if (file == null)
695         {
696           // retrieve the pdb and store it locally
697           AlignmentI pdbseq = null;
698           pdbid = jmb.pdbentry[pi].getId();
699           long hdl = pdbid.hashCode() - System.currentTimeMillis();
700           if (progressBar != null)
701           {
702             progressBar.setProgressBar("Fetching PDB " + pdbid, hdl);
703           }
704           try
705           {
706             pdbseq = pdbclient.getSequenceRecords(pdbid = jmb.pdbentry[pi]
707                     .getId());
708           } catch (OutOfMemoryError oomerror)
709           {
710             new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
711           } catch (Exception ex)
712           {
713             ex.printStackTrace();
714             errormsgs.append("'" + pdbid + "'");
715           }
716           if (progressBar != null)
717           {
718             progressBar.setProgressBar("Finished.", hdl);
719           }
720           if (pdbseq != null)
721           {
722             // just transfer the file name from the first sequence's first
723             // PDBEntry
724             file = new File(((PDBEntry) pdbseq.getSequenceAt(0).getPDBId()
725                     .elementAt(0)).getFile()).getAbsolutePath();
726             jmb.pdbentry[pi].setFile(file);
727
728             files.append(" \"" + Platform.escapeString(file) + "\"");
729           }
730           else
731           {
732             errormsgs.append("'" + pdbid + "' ");
733           }
734         }
735         else
736         {
737           if (curfiles != null && curfiles.length > 0)
738           {
739             addingStructures = true; // already files loaded.
740             for (int c = 0; c < curfiles.length; c++)
741             {
742               if (curfiles[c].equals(file))
743               {
744                 file = null;
745                 break;
746               }
747             }
748           }
749           
750           if (file != null)
751           {
752             fileToLoad.add(file);
753             filePDB.add(jmb.pdbentry[pi]);
754             filePDBpos.add(Integer.valueOf(pi));
755             files.append(" \"" + Platform.escapeString(file) + "\"");
756           }
757         }
758       }
759     } catch (OutOfMemoryError oomerror)
760     {
761       new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
762     } catch (Exception ex)
763     {
764       ex.printStackTrace();
765       errormsgs.append("When retrieving pdbfiles : current was: '" + pdbid
766               + "'");
767     }
768     if (errormsgs.length() > 0)
769     {
770
771       JOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
772               .formatMessage("label.pdb_entries_couldnt_be_retrieved",
773                       new String[]
774                       { errormsgs.toString() }), MessageManager
775               .getString("label.couldnt_load_file"),
776               JOptionPane.ERROR_MESSAGE);
777
778     }
779     long lastnotify = jmb.getLoadNotifiesHandled();
780     if (files.length() > 0)
781     {
782       if (!addingStructures)
783       {
784         try
785         {
786           initChimera("");
787         } catch (Exception ex)
788         {
789           Cache.log.error("Couldn't open Chimera viewer!", ex);
790         }
791       } 
792       int num=-1;
793       for (PDBEntry pe : filePDB)
794       {
795         num++;
796         if (pe.getFile() != null)
797         {
798           try
799           {
800             int pos=filePDBpos.get(num).intValue();
801             jmb.openFile(pe);
802             jmb.addSequence(pos, jmb.sequence[pos]);
803             File fl=new File(pe.getFile());
804             String protocol = AppletFormatAdapter.URL;
805             try
806             {
807               if (fl.exists())
808                 {
809                   protocol = AppletFormatAdapter.FILE;
810                 }
811               } catch (Exception e)
812               {
813               } catch (Error e)
814               {
815               }
816               // Explicitly map to the filename used by Jmol ;
817               jmb.ssm.setMapping(jmb.sequence[pos], null, pe.getFile(),
818                       protocol);
819               // pdbentry[pe].getFile(), protocol);
820           } catch (OutOfMemoryError oomerror)
821           {
822             new OOMWarning(
823                     "When trying to open and map structures from Chimera!",
824                     oomerror);
825           } catch (Exception ex)
826           {
827             Cache.log.error("Couldn't open " + pe.getFile()
828                     + " in Chimera viewer!", ex);
829           } finally
830           {
831             Cache.log.debug("File locations are " + files);
832           }
833         }
834       }
835       // jmb.getPdbFile();
836       jmb.setFinishedInit(true);
837       jmb.setLoadingFromArchive(false);
838       
839       // refresh the sequence colours for the new structure(s)
840       for (AlignmentPanel ap : _colourwith)
841       {
842         jmb.updateColours(ap);
843       }
844       // do superposition if asked to
845       if (alignAddedStructures)
846       {
847         javax.swing.SwingUtilities.invokeLater(new Runnable()
848         {
849           public void run()
850           {
851             alignStructs_withAllAlignPanels();
852           }
853         });
854         alignAddedStructures = false;
855       }
856       addingStructures = false;
857     }
858     _started = false;
859     worker = null;
860   }
861
862   public void pdbFile_actionPerformed(ActionEvent actionEvent)
863   {
864     JalviewFileChooser chooser = new JalviewFileChooser(
865             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
866
867     chooser.setFileView(new JalviewFileView());
868     chooser.setDialogTitle("Save PDB File");
869     chooser.setToolTipText(MessageManager.getString("action.save"));
870
871     int value = chooser.showSaveDialog(this);
872
873     if (value == JalviewFileChooser.APPROVE_OPTION)
874     {
875       try
876       {
877         // TODO: cope with multiple PDB files in view
878         BufferedReader in = new BufferedReader(new FileReader(
879                 jmb.getPdbFile()[0]));
880         File outFile = chooser.getSelectedFile();
881
882         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
883         String data;
884         while ((data = in.readLine()) != null)
885         {
886           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
887           {
888             out.println(data);
889           }
890         }
891         out.close();
892       } catch (Exception ex)
893       {
894         ex.printStackTrace();
895       }
896     }
897   }
898
899   public void viewMapping_actionPerformed(ActionEvent actionEvent)
900   {
901     jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
902     try
903     {
904       for (int pdbe = 0; pdbe < jmb.pdbentry.length; pdbe++)
905       {
906         cap.appendText(jmb.printMapping(jmb.pdbentry[pdbe].getFile()));
907         cap.appendText("\n");
908       }
909     } catch (OutOfMemoryError e)
910     {
911       new OOMWarning(
912               "composing sequence-structure alignments for display in text box.",
913               e);
914       cap.dispose();
915       return;
916     }
917     jalview.gui.Desktop.addInternalFrame(cap,
918             MessageManager.getString("label.pdb_sequence_mapping"), 550,
919             600);
920   }
921
922   /**
923    * DOCUMENT ME!
924    * 
925    * @param e
926    *          DOCUMENT ME!
927    */
928   public void eps_actionPerformed(ActionEvent e)
929   {
930     throw new Error("EPS Generation not yet implemented.");
931   }
932
933   /**
934    * DOCUMENT ME!
935    * 
936    * @param e
937    *          DOCUMENT ME!
938    */
939   public void png_actionPerformed(ActionEvent e)
940   {
941     throw new Error("PNG Generation not yet implemented.");
942   }
943
944   public void jmolColour_actionPerformed(ActionEvent actionEvent)
945   {
946     if (jmolColour.isSelected())
947     {
948       // disable automatic sequence colouring.
949       jmb.setColourBySequence(false);
950     }
951   }
952
953   public void seqColour_actionPerformed(ActionEvent actionEvent)
954   {
955     jmb.setColourBySequence(seqColour.isSelected());
956     if (_colourwith == null)
957     {
958       _colourwith = new Vector<AlignmentPanel>();
959     }
960     if (jmb.isColourBySequence())
961     {
962       if (!jmb.isLoadingFromArchive())
963       {
964         if (_colourwith.size() == 0 && ap != null)
965         {
966           // Make the currently displayed alignment panel the associated view
967           _colourwith.add(ap.alignFrame.alignPanel);
968         }
969       }
970       // Set the colour using the current view for the associated alignframe
971       for (AlignmentPanel ap : _colourwith)
972       {
973         jmb.colourBySequence(ap.av.showSequenceFeatures, ap);
974       }
975     }
976   }
977
978   public void chainColour_actionPerformed(ActionEvent actionEvent)
979   {
980     chainColour.setSelected(true);
981     jmb.colourByChain();
982   }
983
984   public void chargeColour_actionPerformed(ActionEvent actionEvent)
985   {
986     chargeColour.setSelected(true);
987     jmb.colourByCharge();
988   }
989
990   public void zappoColour_actionPerformed(ActionEvent actionEvent)
991   {
992     zappoColour.setSelected(true);
993     jmb.setJalviewColourScheme(new ZappoColourScheme());
994   }
995
996   public void taylorColour_actionPerformed(ActionEvent actionEvent)
997   {
998     taylorColour.setSelected(true);
999     jmb.setJalviewColourScheme(new TaylorColourScheme());
1000   }
1001
1002   public void hydroColour_actionPerformed(ActionEvent actionEvent)
1003   {
1004     hydroColour.setSelected(true);
1005     jmb.setJalviewColourScheme(new HydrophobicColourScheme());
1006   }
1007
1008   public void helixColour_actionPerformed(ActionEvent actionEvent)
1009   {
1010     helixColour.setSelected(true);
1011     jmb.setJalviewColourScheme(new HelixColourScheme());
1012   }
1013
1014   public void strandColour_actionPerformed(ActionEvent actionEvent)
1015   {
1016     strandColour.setSelected(true);
1017     jmb.setJalviewColourScheme(new StrandColourScheme());
1018   }
1019
1020   public void turnColour_actionPerformed(ActionEvent actionEvent)
1021   {
1022     turnColour.setSelected(true);
1023     jmb.setJalviewColourScheme(new TurnColourScheme());
1024   }
1025
1026   public void buriedColour_actionPerformed(ActionEvent actionEvent)
1027   {
1028     buriedColour.setSelected(true);
1029     jmb.setJalviewColourScheme(new BuriedColourScheme());
1030   }
1031
1032   public void purinePyrimidineColour_actionPerformed(ActionEvent actionEvent)
1033   {
1034     setJalviewColourScheme(new PurinePyrimidineColourScheme());
1035   }
1036
1037   public void userColour_actionPerformed(ActionEvent actionEvent)
1038   {
1039     userColour.setSelected(true);
1040     new UserDefinedColours(this, null);
1041   }
1042
1043   public void backGround_actionPerformed(ActionEvent actionEvent)
1044   {
1045     java.awt.Color col = JColorChooser.showDialog(this,
1046             "Select Background Colour", null);
1047     if (col != null)
1048     {
1049       jmb.setBackgroundColour(col);
1050     }
1051   }
1052
1053   public void jmolHelp_actionPerformed(ActionEvent actionEvent)
1054   {
1055     try
1056     {
1057       jalview.util.BrowserLauncher
1058               .openURL("https://www.cgl.ucsf.edu/chimera/docs/UsersGuide");
1059     } catch (Exception ex)
1060     {
1061     }
1062   }
1063
1064   String viewId = null;
1065
1066   public String getViewId()
1067   {
1068     if (viewId == null)
1069     {
1070       viewId = System.currentTimeMillis() + "." + this.hashCode();
1071     }
1072     return viewId;
1073   }
1074
1075   public void updateTitleAndMenus()
1076   {
1077     if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
1078     {
1079       repaint();
1080       return;
1081     }
1082     setChainMenuItems(jmb.chainNames);
1083
1084     this.setTitle(jmb.getViewerTitle());
1085     if (jmb.getPdbFile().length > 1 && jmb.sequence.length > 1)
1086     {
1087       jmolActionMenu.setVisible(true);
1088     }
1089     if (!jmb.isLoadingFromArchive())
1090     {
1091       seqColour_actionPerformed(null);
1092     }
1093   }
1094
1095   protected void buildChimeraActionMenu()
1096   {
1097     if (_alignwith == null)
1098     {
1099       _alignwith = new Vector<AlignmentPanel>();
1100     }
1101     if (_alignwith.size() == 0 && ap != null)
1102     {
1103       _alignwith.add(ap);
1104     }
1105     ;
1106     for (Component c : jmolActionMenu.getMenuComponents())
1107     {
1108       if (c != alignStructs)
1109       {
1110         jmolActionMenu.remove((JMenuItem) c);
1111       }
1112     }
1113     final ItemListener handler;
1114   }
1115
1116   /*
1117    * (non-Javadoc)
1118    * 
1119    * @see
1120    * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
1121    * .ActionEvent)
1122    */
1123   @Override
1124   protected void alignStructs_actionPerformed(ActionEvent actionEvent)
1125   {
1126     alignStructs_withAllAlignPanels();
1127   }
1128
1129   private void alignStructs_withAllAlignPanels()
1130   {
1131     if (ap == null)
1132     {
1133       return;
1134     }
1135     ;
1136     if (_alignwith.size() == 0)
1137     {
1138       _alignwith.add(ap);
1139     }
1140     ;
1141     try
1142     {
1143       AlignmentI[] als = new Alignment[_alignwith.size()];
1144       ColumnSelection[] alc = new ColumnSelection[_alignwith.size()];
1145       int[] alm = new int[_alignwith.size()];
1146       int a = 0;
1147
1148       for (AlignmentPanel ap : _alignwith)
1149       {
1150         als[a] = ap.av.getAlignment();
1151         alm[a] = -1;
1152         alc[a++] = ap.av.getColumnSelection();
1153       }
1154       jmb.superposeStructures(als, alm, alc);
1155     } catch (Exception e)
1156     {
1157       StringBuffer sp = new StringBuffer();
1158       for (AlignmentPanel ap : _alignwith)
1159       {
1160         sp.append("'" + ap.alignFrame.getTitle() + "' ");
1161       }
1162       Cache.log.info("Couldn't align structures with the " + sp.toString()
1163               + "associated alignment panels.", e);
1164
1165     }
1166
1167   }
1168
1169   public void setJalviewColourScheme(ColourSchemeI ucs)
1170   {
1171     jmb.setJalviewColourScheme(ucs);
1172
1173   }
1174
1175   /**
1176    * 
1177    * @param alignment
1178    * @return first alignment panel displaying given alignment, or the default
1179    *         alignment panel
1180    */
1181   public AlignmentPanel getAlignmentPanelFor(AlignmentI alignment)
1182   {
1183     for (AlignmentPanel ap : getAllAlignmentPanels())
1184     {
1185       if (ap.av.getAlignment() == alignment)
1186       {
1187         return ap;
1188       }
1189     }
1190     return ap;
1191   }
1192
1193   /**
1194    * 
1195    * @param ap2
1196    * @return true if this Jmol instance is linked with the given alignPanel
1197    */
1198   public boolean isLinkedWith(AlignmentPanel ap2)
1199   {
1200     return _aps.contains(ap2.av.getSequenceSetId());
1201   }
1202
1203   public boolean isUsedforaligment(AlignmentPanel ap2)
1204   {
1205
1206     return (_alignwith != null) && _alignwith.contains(ap2);
1207   }
1208
1209   public boolean isUsedforcolourby(AlignmentPanel ap2)
1210   {
1211     return (_colourwith != null) && _colourwith.contains(ap2);
1212   }
1213
1214   /**
1215    * 
1216    * @return TRUE if the view is NOT being coloured by sequence associations.
1217    */
1218   public boolean isColouredByJmol()
1219   {
1220     return !jmb.isColourBySequence();
1221   }
1222
1223   public SequenceStructureBinding getBinding()
1224   {
1225     return jmb;
1226   }
1227
1228 }