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