2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
23 import jalview.bin.Cache;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.PDBEntry;
26 import jalview.datamodel.SequenceI;
27 import jalview.ext.rbvi.chimera.ChimeraCommands;
28 import jalview.ext.rbvi.chimera.JalviewChimeraBinding;
29 import jalview.gui.StructureViewer.ViewerType;
30 import jalview.io.DataSourceType;
31 import jalview.io.StructureFile;
32 import jalview.structures.models.AAStructureBindingModel;
33 import jalview.util.BrowserLauncher;
34 import jalview.util.MessageManager;
35 import jalview.util.Platform;
36 import jalview.ws.dbsources.Pdb;
38 import java.awt.event.ActionEvent;
39 import java.awt.event.ActionListener;
40 import java.awt.event.MouseAdapter;
41 import java.awt.event.MouseEvent;
43 import java.io.FileInputStream;
44 import java.io.IOException;
45 import java.io.InputStream;
46 import java.util.ArrayList;
47 import java.util.Collections;
48 import java.util.List;
49 import java.util.Random;
51 import javax.swing.JCheckBoxMenuItem;
52 import javax.swing.JInternalFrame;
53 import javax.swing.JMenu;
54 import javax.swing.JMenuItem;
55 import javax.swing.event.InternalFrameAdapter;
56 import javax.swing.event.InternalFrameEvent;
59 * GUI elements for handling an external chimera display
64 public class ChimeraViewFrame extends StructureViewerBase
66 private JalviewChimeraBinding jmb;
68 private IProgressIndicator progressBar = null;
71 * Path to Chimera session file. This is set when an open Jalview/Chimera
72 * session is saved, or on restore from a Jalview project (if it holds the
73 * filename of any saved Chimera sessions).
75 private String chimeraSessionFile = null;
77 private Random random = new Random();
79 private int myWidth = 500;
81 private int myHeight = 150;
84 * Initialise menu options.
87 protected void initMenus()
91 viewerActionMenu.setText(MessageManager.getString("label.chimera"));
93 viewerColour.setText(MessageManager
94 .getString("label.colour_with_chimera"));
95 viewerColour.setToolTipText(MessageManager
96 .getString("label.let_chimera_manage_structure_colours"));
98 helpItem.setText(MessageManager.getString("label.chimera_help"));
99 savemenu.setVisible(false); // not yet implemented
100 viewMenu.add(fitToWindow);
102 JMenuItem writeFeatures = new JMenuItem(
103 MessageManager.getString("label.create_chimera_attributes"));
104 writeFeatures.setToolTipText(MessageManager
105 .getString("label.create_chimera_attributes_tip"));
106 writeFeatures.addActionListener(new ActionListener()
109 public void actionPerformed(ActionEvent e)
111 sendFeaturesToChimera();
114 viewerActionMenu.add(writeFeatures);
116 final JMenu fetchAttributes = new JMenu(
117 MessageManager.getString("label.fetch_chimera_attributes"));
118 fetchAttributes.setToolTipText(MessageManager
119 .getString("label.fetch_chimera_attributes_tip"));
120 fetchAttributes.addMouseListener(new MouseAdapter()
124 public void mouseEntered(MouseEvent e)
126 buildAttributesMenu(fetchAttributes);
129 viewerActionMenu.add(fetchAttributes);
134 * Query Chimera for its residue attribute names and add them as items off the
137 * @param attributesMenu
139 protected void buildAttributesMenu(JMenu attributesMenu)
141 List<String> atts = jmb.sendChimeraCommand("list resattr", true);
146 attributesMenu.removeAll();
147 Collections.sort(atts);
148 for (String att : atts)
150 final String attName = att.split(" ")[1];
153 * ignore 'jv_*' attributes, as these are Jalview features that have
154 * been transferred to residue attributes in Chimera!
156 if (!attName.startsWith(ChimeraCommands.NAMESPACE_PREFIX))
158 JMenuItem menuItem = new JMenuItem(attName);
159 menuItem.addActionListener(new ActionListener()
162 public void actionPerformed(ActionEvent e)
164 getChimeraAttributes(attName);
167 attributesMenu.add(menuItem);
173 * Read residues in Chimera with the given attribute name, and set as features
174 * on the corresponding sequence positions (if any)
178 protected void getChimeraAttributes(String attName)
180 jmb.copyStructureAttributesToFeatures(attName, getAlignmentPanel());
184 * Send a command to Chimera to create residue attributes for Jalview features
186 * The syntax is: setattr r <attName> <attValue> <atomSpec>
188 * For example: setattr r jv:chain "Ferredoxin-1, Chloroplastic" #0:94.A
190 protected void sendFeaturesToChimera()
192 int count = jmb.sendFeaturesToViewer(getAlignmentPanel());
193 statusBar.setText(MessageManager.formatMessage("label.attributes_set",
198 * add a single PDB structure to a new or existing Chimera view
205 public ChimeraViewFrame(PDBEntry pdbentry, SequenceI[] seq,
206 String[] chains, final AlignmentPanel ap)
209 String pdbId = pdbentry.getId();
212 * If the PDB file is already loaded, the user may just choose to add to an
213 * existing viewer (or cancel)
215 if (addAlreadyLoadedFile(seq, chains, ap, pdbId))
221 * Check if there are other Chimera views involving this alignment and give
222 * user the option to add and align this molecule to one of them (or cancel)
224 if (addToExistingViewer(pdbentry, seq, chains, ap, pdbId))
230 * If the options above are declined or do not apply, show the structure in
233 openNewChimera(ap, new PDBEntry[] { pdbentry },
234 new SequenceI[][] { seq });
238 * Create a helper to manage progress bar display
240 protected void createProgressBar()
242 if (progressBar == null)
244 progressBar = new ProgressBar(statusPanel, statusBar);
248 private void openNewChimera(AlignmentPanel ap, PDBEntry[] pdbentrys,
252 jmb = new JalviewChimeraBindingModel(this,
253 ap.getStructureSelectionManager(), pdbentrys, seqs, null);
254 addAlignmentPanel(ap);
255 useAlignmentPanelForColourbyseq(ap);
257 if (pdbentrys.length > 1)
259 alignAddedStructures = true;
260 useAlignmentPanelForSuperposition(ap);
262 jmb.setColourBySequence(true);
263 setSize(myWidth, myHeight);
266 addingStructures = false;
267 worker = new Thread(this);
270 this.addInternalFrameListener(new InternalFrameAdapter()
273 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
282 * Create a new viewer from saved session state data including Chimera session
285 * @param chimeraSessionFile
289 * @param colourByChimera
290 * @param colourBySequence
293 public ChimeraViewFrame(String chimeraSessionFile,
294 AlignmentPanel alignPanel, PDBEntry[] pdbArray,
295 SequenceI[][] seqsArray, boolean colourByChimera,
296 boolean colourBySequence, String newViewId)
299 setViewId(newViewId);
300 this.chimeraSessionFile = chimeraSessionFile;
301 openNewChimera(alignPanel, pdbArray, seqsArray);
304 jmb.setColourBySequence(false);
305 seqColour.setSelected(false);
306 viewerColour.setSelected(true);
308 else if (colourBySequence)
310 jmb.setColourBySequence(true);
311 seqColour.setSelected(true);
312 viewerColour.setSelected(false);
317 * create a new viewer containing several structures superimposed using the
324 public ChimeraViewFrame(PDBEntry[] pe, SequenceI[][] seqs,
328 openNewChimera(ap, pe, seqs);
332 * Default constructor
334 public ChimeraViewFrame()
339 * closeViewer will decide whether or not to close this frame
340 * depending on whether user chooses to Cancel or not
342 setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
346 * Returns a list of any Chimera viewers in the desktop. The list is
347 * restricted to those linked to the given alignment panel if it is not null.
350 protected List<StructureViewerBase> getViewersFor(AlignmentPanel ap)
352 List<StructureViewerBase> result = new ArrayList<StructureViewerBase>();
353 JInternalFrame[] frames = Desktop.instance.getAllFrames();
355 for (JInternalFrame frame : frames)
357 if (frame instanceof ChimeraViewFrame)
359 if (ap == null || ((StructureViewerBase) frame).isLinkedWith(ap))
361 result.add((StructureViewerBase) frame);
369 * Launch Chimera. If we have a chimera session file name, send Chimera the
370 * command to open its saved session file.
374 jmb.setFinishedInit(false);
375 Desktop.addInternalFrame(this,
376 jmb.getViewerTitle(getViewerName(), true), getBounds().width,
379 if (!jmb.launchChimera())
381 JvOptionPane.showMessageDialog(Desktop.desktop,
382 MessageManager.getString("label.chimera_failed"),
383 MessageManager.getString("label.error_loading_file"),
384 JvOptionPane.ERROR_MESSAGE);
389 if (this.chimeraSessionFile != null)
391 boolean opened = jmb.openSession(chimeraSessionFile);
395 .println("An error occurred opening Chimera session file "
396 + chimeraSessionFile);
400 jmb.startChimeraListener();
404 * Show only the selected chain(s) in the viewer
407 void showSelectedChains()
409 List<String> toshow = new ArrayList<String>();
410 for (int i = 0; i < chainMenu.getItemCount(); i++)
412 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
414 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
415 if (item.isSelected())
417 toshow.add(item.getText());
421 jmb.showChains(toshow);
425 * Close down this instance of Jalview's Chimera viewer, giving the user the
426 * option to close the associated Chimera window (process). They may wish to
427 * keep it open until they have had an opportunity to save any work.
429 * @param closeChimera
430 * if true, close any linked Chimera process; if false, prompt first
433 public void closeViewer(boolean closeChimera)
435 if (jmb != null && jmb.isChimeraRunning())
439 String prompt = MessageManager.formatMessage(
440 "label.confirm_close_chimera",
441 new Object[] { jmb.getViewerTitle(getViewerName(),
443 prompt = JvSwingUtils.wrapTooltip(true, prompt);
444 int confirm = JvOptionPane.showConfirmDialog(this, prompt,
445 MessageManager.getString("label.close_viewer"),
446 JvOptionPane.YES_NO_CANCEL_OPTION);
448 * abort closure if user hits escape or Cancel
450 if (confirm == JvOptionPane.CANCEL_OPTION
451 || confirm == JvOptionPane.CLOSED_OPTION)
455 closeChimera = confirm == JvOptionPane.YES_OPTION;
457 jmb.closeViewer(closeChimera);
459 setAlignmentPanel(null);
463 // TODO: check for memory leaks where instance isn't finalised because jmb
464 // holds a reference to the window
470 * Open any newly added PDB structures in Chimera, having first fetched data
471 * from PDB (if not already saved).
477 // todo - record which pdbids were successfully imported.
478 StringBuilder errormsgs = new StringBuilder(128);
479 StringBuilder files = new StringBuilder(128);
480 List<PDBEntry> filePDB = new ArrayList<PDBEntry>();
481 List<Integer> filePDBpos = new ArrayList<Integer>();
482 PDBEntry thePdbEntry = null;
483 StructureFile pdb = null;
486 String[] curfiles = jmb.getPdbFile(); // files currently in viewer
487 // TODO: replace with reference fetching/transfer code (validate PDBentry
489 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
492 thePdbEntry = jmb.getPdbEntry(pi);
493 if (thePdbEntry.getFile() == null)
496 * Retrieve PDB data, save to file, attach to PDBEntry
498 file = fetchPdbFile(thePdbEntry);
501 errormsgs.append("'" + thePdbEntry.getId() + "' ");
507 * Got file already - ignore if already loaded in Chimera.
509 file = new File(thePdbEntry.getFile()).getAbsoluteFile()
511 if (curfiles != null && curfiles.length > 0)
513 addingStructures = true; // already files loaded.
514 for (int c = 0; c < curfiles.length; c++)
516 if (curfiles[c].equals(file))
526 filePDB.add(thePdbEntry);
527 filePDBpos.add(Integer.valueOf(pi));
528 files.append(" \"" + Platform.escapeString(file) + "\"");
531 } catch (OutOfMemoryError oomerror)
533 new OOMWarning("Retrieving PDB files: " + thePdbEntry.getId(),
535 } catch (Exception ex)
537 ex.printStackTrace();
538 errormsgs.append("When retrieving pdbfiles for '"
539 + thePdbEntry.getId() + "'");
541 if (errormsgs.length() > 0)
544 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
545 .formatMessage("label.pdb_entries_couldnt_be_retrieved",
546 new Object[] { errormsgs.toString() }),
547 MessageManager.getString("label.couldnt_load_file"),
548 JvOptionPane.ERROR_MESSAGE);
551 if (files.length() > 0)
553 jmb.setFinishedInit(false);
554 if (!addingStructures)
559 } catch (Exception ex)
561 Cache.log.error("Couldn't open Chimera viewer!", ex);
565 for (PDBEntry pe : filePDB)
568 if (pe.getFile() != null)
572 int pos = filePDBpos.get(num).intValue();
573 long startTime = startProgressBar(getViewerName() + " "
574 + MessageManager.getString("status.opening_file_for")
577 jmb.addSequence(pos, jmb.getSequence()[pos]);
578 File fl = new File(pe.getFile());
579 DataSourceType protocol = DataSourceType.URL;
584 protocol = DataSourceType.FILE;
586 } catch (Throwable e)
590 stopProgressBar("", startTime);
592 // Explicitly map to the filename used by Chimera ;
593 pdb = jmb.getSsm().setMapping(jmb.getSequence()[pos],
594 jmb.getChains()[pos], pe.getFile(), protocol);
595 stashFoundChains(pdb, pe.getFile());
596 } catch (OutOfMemoryError oomerror)
599 "When trying to open and map structures from Chimera!",
601 } catch (Exception ex)
603 Cache.log.error("Couldn't open " + pe.getFile()
604 + " in Chimera viewer!", ex);
607 Cache.log.debug("File locations are " + files);
613 jmb.setFinishedInit(true);
614 jmb.setLoadingFromArchive(false);
616 // refresh the sequence colours for the new structure(s)
617 for (AlignmentPanel ap : _colourwith)
619 jmb.updateColours(ap);
621 // do superposition if asked to
622 if (Cache.getDefault("AUTOSUPERIMPOSE", true) && alignAddedStructures)
624 new Thread(new Runnable()
629 alignStructs_withAllAlignPanels();
632 alignAddedStructures = false;
634 addingStructures = false;
641 * Fetch PDB data and save to a local file. Returns the full path to the file,
642 * or null if fetch fails.
644 * @param processingEntry
649 private void stashFoundChains(StructureFile pdb, String file)
651 for (int i = 0; i < pdb.getChains().size(); i++)
653 String chid = new String(pdb.getId() + ":"
654 + pdb.getChains().elementAt(i).id);
655 jmb.getChainNames().add(chid);
656 jmb.getChainFile().put(chid, file);
659 private String fetchPdbFile(PDBEntry processingEntry) throws Exception
661 // FIXME: this is duplicated code with Jmol frame ?
662 String filePath = null;
663 Pdb pdbclient = new Pdb();
664 AlignmentI pdbseq = null;
665 String pdbid = processingEntry.getId();
666 long handle = System.currentTimeMillis()
667 + Thread.currentThread().hashCode();
670 * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
672 String msg = MessageManager.formatMessage("status.fetching_pdb",
673 new Object[] { pdbid });
674 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
675 // long hdl = startProgressBar(MessageManager.formatMessage(
676 // "status.fetching_pdb", new Object[]
680 pdbseq = pdbclient.getSequenceRecords(pdbid);
681 } catch (OutOfMemoryError oomerror)
683 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
686 msg = pdbid + " " + MessageManager.getString("label.state_completed");
687 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
688 // stopProgressBar(msg, hdl);
691 * If PDB data were saved and are not invalid (empty alignment), return the
694 if (pdbseq != null && pdbseq.getHeight() > 0)
696 // just use the file name from the first sequence's first PDBEntry
697 filePath = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
698 .elementAt(0).getFile()).getAbsolutePath();
699 processingEntry.setFile(filePath);
705 * Convenience method to update the progress bar if there is one. Be sure to
706 * call stopProgressBar with the returned handle to remove the message.
711 public long startProgressBar(String msg)
713 // TODO would rather have startProgress/stopProgress as the
714 // IProgressIndicator interface
715 long tm = random.nextLong();
716 if (progressBar != null)
718 progressBar.setProgressBar(msg, tm);
724 * End the progress bar with the specified handle, leaving a message (if not
725 * null) on the status bar
730 public void stopProgressBar(String msg, long handle)
732 if (progressBar != null)
734 progressBar.setProgressBar(msg, handle);
739 public void eps_actionPerformed(ActionEvent e)
743 .getString("error.eps_generation_not_implemented"));
747 public void png_actionPerformed(ActionEvent e)
751 .getString("error.png_generation_not_implemented"));
755 public void showHelp_actionPerformed(ActionEvent actionEvent)
760 .openURL("https://www.cgl.ucsf.edu/chimera/docs/UsersGuide");
761 } catch (IOException ex)
767 public AAStructureBindingModel getBinding()
773 * Ask Chimera to save its session to the designated file path, or to a
774 * temporary file if the path is null. Returns the file path if successful,
780 protected String saveSession(String filepath)
782 String pathUsed = filepath;
785 if (pathUsed == null)
787 File tempFile = File.createTempFile("chimera", ".py");
788 tempFile.deleteOnExit();
789 pathUsed = tempFile.getPath();
791 boolean result = jmb.saveSession(pathUsed);
794 this.chimeraSessionFile = pathUsed;
797 } catch (IOException e)
804 * Returns a string representing the state of the Chimera session. This is
805 * done by requesting Chimera to save its session to a temporary file, then
806 * reading the file contents. Returns an empty string on any error.
809 public String getStateInfo()
811 String sessionFile = saveSession(null);
812 if (sessionFile == null)
816 InputStream is = null;
819 File f = new File(sessionFile);
820 byte[] bytes = new byte[(int) f.length()];
821 is = new FileInputStream(sessionFile);
823 return new String(bytes);
824 } catch (IOException e)
834 } catch (IOException e)
843 protected void fitToWindow_actionPerformed()
849 public ViewerType getViewerType()
851 return ViewerType.CHIMERA;
855 protected String getViewerName()
861 * Sends commands to align structures according to associated alignment(s).
866 protected String alignStructs_withAllAlignPanels()
868 String reply = super.alignStructs_withAllAlignPanels();
871 statusBar.setText("Superposition failed: " + reply);