71e90d90ce97f240c00712c672e8791c6d690abc
[jalview.git] / src / jalview / gui / ChimeraViewFrame.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ 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.AlignmentViewPanel;
24 import jalview.api.FeatureRenderer;
25 import jalview.bin.Cache;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.SequenceI;
29 import jalview.ext.rbvi.chimera.ChimeraCommands;
30 import jalview.ext.rbvi.chimera.JalviewChimeraBinding;
31 import jalview.gui.StructureViewer.ViewerType;
32 import jalview.io.DataSourceType;
33 import jalview.io.StructureFile;
34 import jalview.structures.models.AAStructureBindingModel;
35 import jalview.util.BrowserLauncher;
36 import jalview.util.MessageManager;
37 import jalview.util.Platform;
38 import jalview.ws.dbsources.Pdb;
39
40 import java.awt.event.ActionEvent;
41 import java.awt.event.ActionListener;
42 import java.awt.event.MouseAdapter;
43 import java.awt.event.MouseEvent;
44 import java.io.File;
45 import java.io.FileInputStream;
46 import java.io.IOException;
47 import java.io.InputStream;
48 import java.util.ArrayList;
49 import java.util.Collections;
50 import java.util.List;
51 import java.util.Random;
52
53 import javax.swing.JInternalFrame;
54 import javax.swing.JMenu;
55 import javax.swing.JMenuItem;
56 import javax.swing.event.InternalFrameAdapter;
57 import javax.swing.event.InternalFrameEvent;
58
59 /**
60  * GUI elements for handling an external chimera display
61  * 
62  * @author jprocter
63  *
64  */
65 public class ChimeraViewFrame extends StructureViewerBase
66 {
67   private JalviewChimeraBinding jmb;
68
69   private IProgressIndicator progressBar = null;
70
71   /*
72    * Path to Chimera session file. This is set when an open Jalview/Chimera
73    * session is saved, or on restore from a Jalview project (if it holds the
74    * filename of any saved Chimera sessions).
75    */
76   private String chimeraSessionFile = null;
77
78   private Random random = new Random();
79
80   private int myWidth = 500;
81
82   private int myHeight = 150;
83
84   /**
85    * Initialise menu options.
86    */
87   @Override
88   protected void initMenus()
89   {
90     super.initMenus();
91
92     viewerActionMenu.setText(MessageManager.getString("label.chimera"));
93
94     viewerColour
95             .setText(MessageManager.getString("label.colour_with_chimera"));
96     viewerColour.setToolTipText(MessageManager
97             .getString("label.let_chimera_manage_structure_colours"));
98
99     helpItem.setText(MessageManager.getString("label.chimera_help"));
100     savemenu.setVisible(false); // not yet implemented
101     viewMenu.add(fitToWindow);
102
103     JMenuItem writeFeatures = new JMenuItem(
104             MessageManager.getString("label.create_chimera_attributes"));
105     writeFeatures.setToolTipText(MessageManager
106             .getString("label.create_chimera_attributes_tip"));
107     writeFeatures.addActionListener(new ActionListener()
108     {
109       @Override
110       public void actionPerformed(ActionEvent e)
111       {
112         sendFeaturesToChimera();
113       }
114     });
115     viewerActionMenu.add(writeFeatures);
116
117     final JMenu fetchAttributes = new JMenu(
118             MessageManager.getString("label.fetch_chimera_attributes"));
119     fetchAttributes.setToolTipText(
120             MessageManager.getString("label.fetch_chimera_attributes_tip"));
121     fetchAttributes.addMouseListener(new MouseAdapter()
122     {
123
124       @Override
125       public void mouseEntered(MouseEvent e)
126       {
127         buildAttributesMenu(fetchAttributes);
128       }
129     });
130     viewerActionMenu.add(fetchAttributes);
131   }
132
133   /**
134    * Query Chimera for its residue attribute names and add them as items off the
135    * attributes menu
136    * 
137    * @param attributesMenu
138    */
139   protected void buildAttributesMenu(JMenu attributesMenu)
140   {
141     List<String> atts = jmb.sendChimeraCommand("list resattr", true);
142     if (atts == null)
143     {
144       return;
145     }
146     attributesMenu.removeAll();
147     Collections.sort(atts);
148     for (String att : atts)
149     {
150       final String attName = att.split(" ")[1];
151
152       /*
153        * ignore 'jv_*' attributes, as these are Jalview features that have
154        * been transferred to residue attributes in Chimera!
155        */
156       if (!attName.startsWith(ChimeraCommands.NAMESPACE_PREFIX))
157       {
158         JMenuItem menuItem = new JMenuItem(attName);
159         menuItem.addActionListener(new ActionListener()
160         {
161           @Override
162           public void actionPerformed(ActionEvent e)
163           {
164             getChimeraAttributes(attName);
165           }
166         });
167         attributesMenu.add(menuItem);
168       }
169     }
170   }
171
172   /**
173    * Read residues in Chimera with the given attribute name, and set as features
174    * on the corresponding sequence positions (if any)
175    * 
176    * @param attName
177    */
178   protected void getChimeraAttributes(String attName)
179   {
180     jmb.copyStructureAttributesToFeatures(attName, getAlignmentPanel());
181   }
182
183   /**
184    * Send a command to Chimera to create residue attributes for Jalview features
185    * <p>
186    * The syntax is: setattr r <attName> <attValue> <atomSpec>
187    * <p>
188    * For example: setattr r jv:chain "Ferredoxin-1, Chloroplastic" #0:94.A
189    */
190   protected void sendFeaturesToChimera()
191   {
192     int count = jmb.sendFeaturesToViewer(getAlignmentPanel());
193     statusBar.setText(
194             MessageManager.formatMessage("label.attributes_set", count));
195   }
196
197   /**
198    * open a single PDB structure in a new Chimera view
199    * 
200    * @param pdbentry
201    * @param seq
202    * @param chains
203    * @param ap
204    */
205   public ChimeraViewFrame(PDBEntry pdbentry, SequenceI[] seq,
206           String[] chains, final AlignmentPanel ap)
207   {
208     this();
209
210     openNewChimera(ap, new PDBEntry[] { pdbentry },
211             new SequenceI[][]
212             { seq });
213   }
214
215   /**
216    * Create a helper to manage progress bar display
217    */
218   protected void createProgressBar()
219   {
220     if (progressBar == null)
221     {
222       progressBar = new ProgressBar(statusPanel, statusBar);
223     }
224   }
225
226   private void openNewChimera(AlignmentPanel ap, PDBEntry[] pdbentrys,
227           SequenceI[][] seqs)
228   {
229     createProgressBar();
230     jmb = new JalviewChimeraBindingModel(this,
231             ap.getStructureSelectionManager(), pdbentrys, seqs, null);
232     addAlignmentPanel(ap);
233     useAlignmentPanelForColourbyseq(ap);
234
235     if (pdbentrys.length > 1)
236     {
237       useAlignmentPanelForSuperposition(ap);
238     }
239     jmb.setColourBySequence(true);
240     setSize(myWidth, myHeight);
241     initMenus();
242
243     addingStructures = false;
244     worker = new Thread(this);
245     worker.start();
246
247     this.addInternalFrameListener(new InternalFrameAdapter()
248     {
249       @Override
250       public void internalFrameClosing(
251               InternalFrameEvent internalFrameEvent)
252       {
253         closeViewer(false);
254       }
255     });
256
257   }
258
259   /**
260    * Create a new viewer from saved session state data including Chimera session
261    * file
262    * 
263    * @param chimeraSessionFile
264    * @param alignPanel
265    * @param pdbArray
266    * @param seqsArray
267    * @param colourByChimera
268    * @param colourBySequence
269    * @param newViewId
270    */
271   public ChimeraViewFrame(String chimeraSessionFile,
272           AlignmentPanel alignPanel, PDBEntry[] pdbArray,
273           SequenceI[][] seqsArray, boolean colourByChimera,
274           boolean colourBySequence, String newViewId)
275   {
276     this();
277     setViewId(newViewId);
278     this.chimeraSessionFile = chimeraSessionFile;
279     openNewChimera(alignPanel, pdbArray, seqsArray);
280     if (colourByChimera)
281     {
282       jmb.setColourBySequence(false);
283       seqColour.setSelected(false);
284       viewerColour.setSelected(true);
285     }
286     else if (colourBySequence)
287     {
288       jmb.setColourBySequence(true);
289       seqColour.setSelected(true);
290       viewerColour.setSelected(false);
291     }
292   }
293
294   /**
295    * create a new viewer containing several structures, optionally superimposed
296    * using the given alignPanel.
297    * 
298    * @param pe
299    * @param seqs
300    * @param ap
301    */
302   public ChimeraViewFrame(PDBEntry[] pe, boolean alignAdded,
303           SequenceI[][] seqs,
304           AlignmentPanel ap)
305   {
306     this();
307     setAlignAddedStructures(alignAdded);
308     openNewChimera(ap, pe, seqs);
309   }
310
311   /**
312    * Default constructor
313    */
314   public ChimeraViewFrame()
315   {
316     super();
317
318     /*
319      * closeViewer will decide whether or not to close this frame
320      * depending on whether user chooses to Cancel or not
321      */
322     setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
323   }
324
325   /**
326    * Launch Chimera. If we have a chimera session file name, send Chimera the
327    * command to open its saved session file.
328    */
329   void initChimera()
330   {
331     jmb.setFinishedInit(false);
332     Desktop.addInternalFrame(this,
333             jmb.getViewerTitle(getViewerName(), true), getBounds().width,
334             getBounds().height);
335
336     if (!jmb.launchChimera())
337     {
338       JvOptionPane.showMessageDialog(Desktop.desktop,
339               MessageManager.getString("label.chimera_failed"),
340               MessageManager.getString("label.error_loading_file"),
341               JvOptionPane.ERROR_MESSAGE);
342       this.dispose();
343       return;
344     }
345
346     if (this.chimeraSessionFile != null)
347     {
348       boolean opened = jmb.openSession(chimeraSessionFile);
349       if (!opened)
350       {
351         System.err.println("An error occurred opening Chimera session file "
352                 + chimeraSessionFile);
353       }
354     }
355
356     jmb.startChimeraListener();
357   }
358
359   /**
360    * Close down this instance of Jalview's Chimera viewer, giving the user the
361    * option to close the associated Chimera window (process). They may wish to
362    * keep it open until they have had an opportunity to save any work.
363    * 
364    * @param closeChimera
365    *          if true, close any linked Chimera process; if false, prompt first
366    */
367   @Override
368   public void closeViewer(boolean closeChimera)
369   {
370     if (jmb != null && jmb.isChimeraRunning())
371     {
372       if (!closeChimera)
373       {
374         String prompt = MessageManager
375                 .formatMessage("label.confirm_close_chimera", new Object[]
376                 { jmb.getViewerTitle(getViewerName(), false) });
377         prompt = JvSwingUtils.wrapTooltip(true, prompt);
378         int confirm = JvOptionPane.showConfirmDialog(this, prompt,
379                 MessageManager.getString("label.close_viewer"),
380                 JvOptionPane.YES_NO_CANCEL_OPTION);
381         /*
382          * abort closure if user hits escape or Cancel
383          */
384         if (confirm == JvOptionPane.CANCEL_OPTION
385                 || confirm == JvOptionPane.CLOSED_OPTION)
386         {
387           return;
388         }
389         closeChimera = confirm == JvOptionPane.YES_OPTION;
390       }
391       jmb.closeViewer(closeChimera);
392     }
393     setAlignmentPanel(null);
394     _aps.clear();
395     _alignwith.clear();
396     _colourwith.clear();
397     // TODO: check for memory leaks where instance isn't finalised because jmb
398     // holds a reference to the window
399     jmb = null;
400     dispose();
401   }
402
403   /**
404    * Open any newly added PDB structures in Chimera, having first fetched data
405    * from PDB (if not already saved).
406    */
407   @Override
408   public void run()
409   {
410     _started = true;
411     // todo - record which pdbids were successfully imported.
412     StringBuilder errormsgs = new StringBuilder(128);
413     StringBuilder files = new StringBuilder(128);
414     List<PDBEntry> filePDB = new ArrayList<>();
415     List<Integer> filePDBpos = new ArrayList<>();
416     PDBEntry thePdbEntry = null;
417     StructureFile pdb = null;
418     try
419     {
420       String[] curfiles = jmb.getStructureFiles(); // files currently in viewer
421       // TODO: replace with reference fetching/transfer code (validate PDBentry
422       // as a DBRef?)
423       for (int pi = 0; pi < jmb.getPdbCount(); pi++)
424       {
425         String file = null;
426         thePdbEntry = jmb.getPdbEntry(pi);
427         if (thePdbEntry.getFile() == null)
428         {
429           /*
430            * Retrieve PDB data, save to file, attach to PDBEntry
431            */
432           file = fetchPdbFile(thePdbEntry);
433           if (file == null)
434           {
435             errormsgs.append("'" + thePdbEntry.getId() + "' ");
436           }
437         }
438         else
439         {
440           /*
441            * Got file already - ignore if already loaded in Chimera.
442            */
443           file = new File(thePdbEntry.getFile()).getAbsoluteFile()
444                   .getPath();
445           if (curfiles != null && curfiles.length > 0)
446           {
447             addingStructures = true; // already files loaded.
448             for (int c = 0; c < curfiles.length; c++)
449             {
450               if (curfiles[c].equals(file))
451               {
452                 file = null;
453                 break;
454               }
455             }
456           }
457         }
458         if (file != null)
459         {
460           filePDB.add(thePdbEntry);
461           filePDBpos.add(Integer.valueOf(pi));
462           files.append(" \"" + Platform.escapeBackslashes(file) + "\"");
463         }
464       }
465     } catch (OutOfMemoryError oomerror)
466     {
467       new OOMWarning("Retrieving PDB files: " + thePdbEntry.getId(),
468               oomerror);
469     } catch (Exception ex)
470     {
471       ex.printStackTrace();
472       errormsgs.append(
473               "When retrieving pdbfiles for '" + thePdbEntry.getId() + "'");
474     }
475     if (errormsgs.length() > 0)
476     {
477
478       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
479               MessageManager.formatMessage(
480                       "label.pdb_entries_couldnt_be_retrieved", new Object[]
481                       { errormsgs.toString() }),
482               MessageManager.getString("label.couldnt_load_file"),
483               JvOptionPane.ERROR_MESSAGE);
484     }
485
486     if (files.length() > 0)
487     {
488       jmb.setFinishedInit(false);
489       if (!addingStructures)
490       {
491         try
492         {
493           initChimera();
494         } catch (Exception ex)
495         {
496           Cache.log.error("Couldn't open Chimera viewer!", ex);
497         }
498       }
499       int num = -1;
500       for (PDBEntry pe : filePDB)
501       {
502         num++;
503         if (pe.getFile() != null)
504         {
505           try
506           {
507             int pos = filePDBpos.get(num).intValue();
508             long startTime = startProgressBar(getViewerName() + " "
509                     + MessageManager.getString("status.opening_file_for")
510                     + " " + pe.getId());
511             jmb.openFile(pe);
512             jmb.addSequence(pos, jmb.getSequence()[pos]);
513             File fl = new File(pe.getFile());
514             DataSourceType protocol = DataSourceType.URL;
515             try
516             {
517               if (fl.exists())
518               {
519                 protocol = DataSourceType.FILE;
520               }
521             } catch (Throwable e)
522             {
523             } finally
524             {
525               stopProgressBar("", startTime);
526             }
527             // Explicitly map to the filename used by Chimera ;
528
529             pdb = jmb.getSsm().setMapping(jmb.getSequence()[pos],
530                     jmb.getChains()[pos], pe.getFile(), protocol,
531                     progressBar);
532             stashFoundChains(pdb, pe.getFile());
533
534           } catch (OutOfMemoryError oomerror)
535           {
536             new OOMWarning(
537                     "When trying to open and map structures from Chimera!",
538                     oomerror);
539           } catch (Exception ex)
540           {
541             Cache.log.error(
542                     "Couldn't open " + pe.getFile() + " in Chimera viewer!",
543                     ex);
544           } finally
545           {
546             Cache.log.debug("File locations are " + files);
547           }
548         }
549       }
550
551       jmb.refreshGUI();
552       jmb.setFinishedInit(true);
553       jmb.setLoadingFromArchive(false);
554
555       /*
556        * ensure that any newly discovered features (e.g. RESNUM)
557        * are added to any open feature settings dialog
558        */
559       FeatureRenderer fr = getBinding().getFeatureRenderer(null);
560       if (fr != null)
561       {
562         fr.featuresAdded();
563       }
564
565       // refresh the sequence colours for the new structure(s)
566       for (AlignmentViewPanel avp : _colourwith)
567       {
568         jmb.updateColours(avp);
569       }
570       // do superposition if asked to
571       if (alignAddedStructures)
572       {
573         new Thread(new Runnable()
574         {
575           @Override
576           public void run()
577           {
578             alignStructs_withAllAlignPanels();
579           }
580         }).start();
581       }
582       addingStructures = false;
583     }
584     _started = false;
585     worker = null;
586   }
587
588   /**
589    * Fetch PDB data and save to a local file. Returns the full path to the file,
590    * or null if fetch fails. TODO: refactor to common with Jmol ? duplication
591    * 
592    * @param processingEntry
593    * @return
594    * @throws Exception
595    */
596
597   private void stashFoundChains(StructureFile pdb, String file)
598   {
599     for (int i = 0; i < pdb.getChains().size(); i++)
600     {
601       String chid = new String(
602               pdb.getId() + ":" + pdb.getChains().elementAt(i).id);
603       jmb.getChainNames().add(chid);
604       jmb.getChainFile().put(chid, file);
605     }
606   }
607
608   private String fetchPdbFile(PDBEntry processingEntry) throws Exception
609   {
610     String filePath = null;
611     Pdb pdbclient = new Pdb();
612     AlignmentI pdbseq = null;
613     String pdbid = processingEntry.getId();
614     long handle = System.currentTimeMillis()
615             + Thread.currentThread().hashCode();
616
617     /*
618      * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
619      */
620     String msg = MessageManager.formatMessage("status.fetching_pdb",
621             new Object[]
622             { pdbid });
623     getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
624     // long hdl = startProgressBar(MessageManager.formatMessage(
625     // "status.fetching_pdb", new Object[]
626     // { pdbid }));
627     try
628     {
629       pdbseq = pdbclient.getSequenceRecords(pdbid);
630     } catch (OutOfMemoryError oomerror)
631     {
632       new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
633     } finally
634     {
635       msg = pdbid + " " + MessageManager.getString("label.state_completed");
636       getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
637       // stopProgressBar(msg, hdl);
638     }
639     /*
640      * If PDB data were saved and are not invalid (empty alignment), return the
641      * file path.
642      */
643     if (pdbseq != null && pdbseq.getHeight() > 0)
644     {
645       // just use the file name from the first sequence's first PDBEntry
646       filePath = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
647               .elementAt(0).getFile()).getAbsolutePath();
648       processingEntry.setFile(filePath);
649     }
650     return filePath;
651   }
652
653   /**
654    * Convenience method to update the progress bar if there is one. Be sure to
655    * call stopProgressBar with the returned handle to remove the message.
656    * 
657    * @param msg
658    * @param handle
659    */
660   public long startProgressBar(String msg)
661   {
662     // TODO would rather have startProgress/stopProgress as the
663     // IProgressIndicator interface
664     long tm = random.nextLong();
665     if (progressBar != null)
666     {
667       progressBar.setProgressBar(msg, tm);
668     }
669     return tm;
670   }
671
672   /**
673    * End the progress bar with the specified handle, leaving a message (if not
674    * null) on the status bar
675    * 
676    * @param msg
677    * @param handle
678    */
679   public void stopProgressBar(String msg, long handle)
680   {
681     if (progressBar != null)
682     {
683       progressBar.setProgressBar(msg, handle);
684     }
685   }
686
687   @Override
688   public void eps_actionPerformed(ActionEvent e)
689   {
690     throw new Error(MessageManager
691             .getString("error.eps_generation_not_implemented"));
692   }
693
694   @Override
695   public void png_actionPerformed(ActionEvent e)
696   {
697     throw new Error(MessageManager
698             .getString("error.png_generation_not_implemented"));
699   }
700
701   @Override
702   public void showHelp_actionPerformed(ActionEvent actionEvent)
703   {
704     try
705     {
706       BrowserLauncher
707               .openURL("https://www.cgl.ucsf.edu/chimera/docs/UsersGuide");
708     } catch (IOException ex)
709     {
710     }
711   }
712
713   @Override
714   public AAStructureBindingModel getBinding()
715   {
716     return jmb;
717   }
718
719   /**
720    * Ask Chimera to save its session to the designated file path, or to a
721    * temporary file if the path is null. Returns the file path if successful,
722    * else null.
723    * 
724    * @param filepath
725    * @see getStateInfo
726    */
727   protected String saveSession(String filepath)
728   {
729     String pathUsed = filepath;
730     try
731     {
732       if (pathUsed == null)
733       {
734         File tempFile = File.createTempFile("chimera", ".py");
735         tempFile.deleteOnExit();
736         pathUsed = tempFile.getPath();
737       }
738       boolean result = jmb.saveSession(pathUsed);
739       if (result)
740       {
741         this.chimeraSessionFile = pathUsed;
742         return pathUsed;
743       }
744     } catch (IOException e)
745     {
746     }
747     return null;
748   }
749
750   /**
751    * Returns a string representing the state of the Chimera session. This is
752    * done by requesting Chimera to save its session to a temporary file, then
753    * reading the file contents. Returns an empty string on any error.
754    */
755   @Override
756   public String getStateInfo()
757   {
758     String sessionFile = saveSession(null);
759     if (sessionFile == null)
760     {
761       return "";
762     }
763     InputStream is = null;
764     try
765     {
766       File f = new File(sessionFile);
767       byte[] bytes = new byte[(int) f.length()];
768       is = new FileInputStream(sessionFile);
769       is.read(bytes);
770       return new String(bytes);
771     } catch (IOException e)
772     {
773       return "";
774     } finally
775     {
776       if (is != null)
777       {
778         try
779         {
780           is.close();
781         } catch (IOException e)
782         {
783           // ignore
784         }
785       }
786     }
787   }
788
789   @Override
790   protected void fitToWindow_actionPerformed()
791   {
792     jmb.focusView();
793   }
794
795   @Override
796   public ViewerType getViewerType()
797   {
798     return ViewerType.CHIMERA;
799   }
800
801   @Override
802   protected String getViewerName()
803   {
804     return "Chimera";
805   }
806
807   /**
808    * Sends commands to align structures according to associated alignment(s).
809    * 
810    * @return
811    */
812   @Override
813   protected String alignStructs_withAllAlignPanels()
814   {
815     String reply = super.alignStructs_withAllAlignPanels();
816     statusBar.setText(
817             reply == null ? " " : "Superposition failed: " + reply);
818     return reply;
819   }
820
821   @Override
822   protected IProgressIndicator getIProgressIndicator()
823   {
824     return progressBar;
825   }
826 }