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