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.api.FeatureRenderer;
24 import jalview.bin.Cache;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.PDBEntry;
27 import jalview.datamodel.SequenceI;
28 import jalview.ext.rbvi.chimera.ChimeraCommands;
29 import jalview.ext.rbvi.chimera.JalviewChimeraBinding;
30 import jalview.gui.StructureViewer.ViewerType;
31 import jalview.io.DataSourceType;
32 import jalview.io.StructureFile;
33 import jalview.structures.models.AAStructureBindingModel;
34 import jalview.util.BrowserLauncher;
35 import jalview.util.MessageManager;
36 import jalview.util.Platform;
37 import jalview.ws.dbsources.Pdb;
39 import java.awt.event.ActionEvent;
40 import java.awt.event.ActionListener;
41 import java.awt.event.MouseAdapter;
42 import java.awt.event.MouseEvent;
44 import java.io.FileInputStream;
45 import java.io.IOException;
46 import java.io.InputStream;
47 import java.util.ArrayList;
48 import java.util.Collections;
49 import java.util.List;
50 import java.util.Random;
52 import javax.swing.JCheckBoxMenuItem;
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;
60 * GUI elements for handling an external chimera display
65 public class ChimeraViewFrame extends StructureViewerBase
67 private JalviewChimeraBinding jmb;
69 private IProgressIndicator progressBar = null;
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).
76 private String chimeraSessionFile = null;
78 private Random random = new Random();
80 private int myWidth = 500;
82 private int myHeight = 150;
85 * Initialise menu options.
88 protected void initMenus()
92 viewerActionMenu.setText(MessageManager.getString("label.chimera"));
94 viewerColour.setText(MessageManager
95 .getString("label.colour_with_chimera"));
96 viewerColour.setToolTipText(MessageManager
97 .getString("label.let_chimera_manage_structure_colours"));
99 helpItem.setText(MessageManager.getString("label.chimera_help"));
100 savemenu.setVisible(false); // not yet implemented
101 viewMenu.add(fitToWindow);
104 * exchange of Jalview features and Chimera attributes is for now
105 * an optionally enabled experimental feature
107 if (Desktop.instance.showExperimental())
109 JMenuItem writeFeatures = new JMenuItem(
110 MessageManager.getString("label.create_chimera_attributes"));
111 writeFeatures.setToolTipText(MessageManager
112 .getString("label.create_chimera_attributes_tip"));
113 writeFeatures.addActionListener(new ActionListener()
116 public void actionPerformed(ActionEvent e)
118 sendFeaturesToChimera();
121 viewerActionMenu.add(writeFeatures);
123 final JMenu fetchAttributes = new JMenu(
124 MessageManager.getString("label.fetch_chimera_attributes"));
125 fetchAttributes.setToolTipText(MessageManager
126 .getString("label.fetch_chimera_attributes_tip"));
127 fetchAttributes.addMouseListener(new MouseAdapter()
131 public void mouseEntered(MouseEvent e)
133 buildAttributesMenu(fetchAttributes);
136 viewerActionMenu.add(fetchAttributes);
141 * Query Chimera for its residue attribute names and add them as items off the
144 * @param attributesMenu
146 protected void buildAttributesMenu(JMenu attributesMenu)
148 List<String> atts = jmb.sendChimeraCommand("list resattr", true);
153 attributesMenu.removeAll();
154 Collections.sort(atts);
155 for (String att : atts)
157 final String attName = att.split(" ")[1];
160 * ignore 'jv_*' attributes, as these are Jalview features that have
161 * been transferred to residue attributes in Chimera!
163 if (!attName.startsWith(ChimeraCommands.NAMESPACE_PREFIX))
165 JMenuItem menuItem = new JMenuItem(attName);
166 menuItem.addActionListener(new ActionListener()
169 public void actionPerformed(ActionEvent e)
171 getChimeraAttributes(attName);
174 attributesMenu.add(menuItem);
180 * Read residues in Chimera with the given attribute name, and set as features
181 * on the corresponding sequence positions (if any)
185 protected void getChimeraAttributes(String attName)
187 jmb.copyStructureAttributesToFeatures(attName, getAlignmentPanel());
191 * Send a command to Chimera to create residue attributes for Jalview features
193 * The syntax is: setattr r <attName> <attValue> <atomSpec>
195 * For example: setattr r jv:chain "Ferredoxin-1, Chloroplastic" #0:94.A
197 protected void sendFeaturesToChimera()
199 int count = jmb.sendFeaturesToViewer(getAlignmentPanel());
200 statusBar.setText(MessageManager.formatMessage("label.attributes_set",
205 * add a single PDB structure to a new or existing Chimera view
212 public ChimeraViewFrame(PDBEntry pdbentry, SequenceI[] seq,
213 String[] chains, final AlignmentPanel ap)
216 String pdbId = pdbentry.getId();
219 * If the PDB file is already loaded, the user may just choose to add to an
220 * existing viewer (or cancel)
222 if (addAlreadyLoadedFile(seq, chains, ap, pdbId))
228 * Check if there are other Chimera views involving this alignment and give
229 * user the option to add and align this molecule to one of them (or cancel)
231 if (addToExistingViewer(pdbentry, seq, chains, ap, pdbId))
237 * If the options above are declined or do not apply, show the structure in
240 openNewChimera(ap, new PDBEntry[] { pdbentry },
241 new SequenceI[][] { seq });
245 * Create a helper to manage progress bar display
247 protected void createProgressBar()
249 if (progressBar == null)
251 progressBar = new ProgressBar(statusPanel, statusBar);
255 private void openNewChimera(AlignmentPanel ap, PDBEntry[] pdbentrys,
259 jmb = new JalviewChimeraBindingModel(this,
260 ap.getStructureSelectionManager(), pdbentrys, seqs, null);
261 addAlignmentPanel(ap);
262 useAlignmentPanelForColourbyseq(ap);
264 if (pdbentrys.length > 1)
266 alignAddedStructures = true;
267 useAlignmentPanelForSuperposition(ap);
269 jmb.setColourBySequence(true);
270 setSize(myWidth, myHeight);
273 addingStructures = false;
274 worker = new Thread(this);
277 this.addInternalFrameListener(new InternalFrameAdapter()
280 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
289 * Create a new viewer from saved session state data including Chimera session
292 * @param chimeraSessionFile
296 * @param colourByChimera
297 * @param colourBySequence
300 public ChimeraViewFrame(String chimeraSessionFile,
301 AlignmentPanel alignPanel, PDBEntry[] pdbArray,
302 SequenceI[][] seqsArray, boolean colourByChimera,
303 boolean colourBySequence, String newViewId)
306 setViewId(newViewId);
307 this.chimeraSessionFile = chimeraSessionFile;
308 openNewChimera(alignPanel, pdbArray, seqsArray);
311 jmb.setColourBySequence(false);
312 seqColour.setSelected(false);
313 viewerColour.setSelected(true);
315 else if (colourBySequence)
317 jmb.setColourBySequence(true);
318 seqColour.setSelected(true);
319 viewerColour.setSelected(false);
324 * create a new viewer containing several structures superimposed using the
331 public ChimeraViewFrame(PDBEntry[] pe, SequenceI[][] seqs,
335 openNewChimera(ap, pe, seqs);
339 * Default constructor
341 public ChimeraViewFrame()
346 * closeViewer will decide whether or not to close this frame
347 * depending on whether user chooses to Cancel or not
349 setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
353 * Returns a list of any Chimera viewers in the desktop. The list is
354 * restricted to those linked to the given alignment panel if it is not null.
357 protected List<StructureViewerBase> getViewersFor(AlignmentPanel ap)
359 List<StructureViewerBase> result = new ArrayList<StructureViewerBase>();
360 JInternalFrame[] frames = Desktop.instance.getAllFrames();
362 for (JInternalFrame frame : frames)
364 if (frame instanceof ChimeraViewFrame)
366 if (ap == null || ((StructureViewerBase) frame).isLinkedWith(ap))
368 result.add((StructureViewerBase) frame);
376 * Launch Chimera. If we have a chimera session file name, send Chimera the
377 * command to open its saved session file.
381 jmb.setFinishedInit(false);
382 Desktop.addInternalFrame(this,
383 jmb.getViewerTitle(getViewerName(), true), getBounds().width,
386 if (!jmb.launchChimera())
388 JvOptionPane.showMessageDialog(Desktop.desktop,
389 MessageManager.getString("label.chimera_failed"),
390 MessageManager.getString("label.error_loading_file"),
391 JvOptionPane.ERROR_MESSAGE);
396 if (this.chimeraSessionFile != null)
398 boolean opened = jmb.openSession(chimeraSessionFile);
402 .println("An error occurred opening Chimera session file "
403 + chimeraSessionFile);
407 jmb.startChimeraListener();
411 * Show only the selected chain(s) in the viewer
414 void showSelectedChains()
416 List<String> toshow = new ArrayList<String>();
417 for (int i = 0; i < chainMenu.getItemCount(); i++)
419 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
421 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
422 if (item.isSelected())
424 toshow.add(item.getText());
428 jmb.showChains(toshow);
432 * Close down this instance of Jalview's Chimera viewer, giving the user the
433 * option to close the associated Chimera window (process). They may wish to
434 * keep it open until they have had an opportunity to save any work.
436 * @param closeChimera
437 * if true, close any linked Chimera process; if false, prompt first
440 public void closeViewer(boolean closeChimera)
442 if (jmb != null && jmb.isChimeraRunning())
446 String prompt = MessageManager.formatMessage(
447 "label.confirm_close_chimera",
448 new Object[] { jmb.getViewerTitle(getViewerName(),
450 prompt = JvSwingUtils.wrapTooltip(true, prompt);
451 int confirm = JvOptionPane.showConfirmDialog(this, prompt,
452 MessageManager.getString("label.close_viewer"),
453 JvOptionPane.YES_NO_CANCEL_OPTION);
455 * abort closure if user hits escape or Cancel
457 if (confirm == JvOptionPane.CANCEL_OPTION
458 || confirm == JvOptionPane.CLOSED_OPTION)
462 closeChimera = confirm == JvOptionPane.YES_OPTION;
464 jmb.closeViewer(closeChimera);
466 setAlignmentPanel(null);
470 // TODO: check for memory leaks where instance isn't finalised because jmb
471 // holds a reference to the window
477 * Open any newly added PDB structures in Chimera, having first fetched data
478 * from PDB (if not already saved).
484 // todo - record which pdbids were successfully imported.
485 StringBuilder errormsgs = new StringBuilder(128);
486 StringBuilder files = new StringBuilder(128);
487 List<PDBEntry> filePDB = new ArrayList<PDBEntry>();
488 List<Integer> filePDBpos = new ArrayList<Integer>();
489 PDBEntry thePdbEntry = null;
490 StructureFile pdb = null;
493 String[] curfiles = jmb.getStructureFiles(); // files currently in viewer
494 // TODO: replace with reference fetching/transfer code (validate PDBentry
496 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
499 thePdbEntry = jmb.getPdbEntry(pi);
500 if (thePdbEntry.getFile() == null)
503 * Retrieve PDB data, save to file, attach to PDBEntry
505 file = fetchPdbFile(thePdbEntry);
508 errormsgs.append("'" + thePdbEntry.getId() + "' ");
514 * Got file already - ignore if already loaded in Chimera.
516 file = new File(thePdbEntry.getFile()).getAbsoluteFile()
518 if (curfiles != null && curfiles.length > 0)
520 addingStructures = true; // already files loaded.
521 for (int c = 0; c < curfiles.length; c++)
523 if (curfiles[c].equals(file))
533 filePDB.add(thePdbEntry);
534 filePDBpos.add(Integer.valueOf(pi));
535 files.append(" \"" + Platform.escapeString(file) + "\"");
538 } catch (OutOfMemoryError oomerror)
540 new OOMWarning("Retrieving PDB files: " + thePdbEntry.getId(),
542 } catch (Exception ex)
544 ex.printStackTrace();
545 errormsgs.append("When retrieving pdbfiles for '"
546 + thePdbEntry.getId() + "'");
548 if (errormsgs.length() > 0)
551 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
552 .formatMessage("label.pdb_entries_couldnt_be_retrieved",
553 new Object[] { errormsgs.toString() }),
554 MessageManager.getString("label.couldnt_load_file"),
555 JvOptionPane.ERROR_MESSAGE);
558 if (files.length() > 0)
560 jmb.setFinishedInit(false);
561 if (!addingStructures)
566 } catch (Exception ex)
568 Cache.log.error("Couldn't open Chimera viewer!", ex);
572 for (PDBEntry pe : filePDB)
575 if (pe.getFile() != null)
579 int pos = filePDBpos.get(num).intValue();
580 long startTime = startProgressBar(getViewerName() + " "
581 + MessageManager.getString("status.opening_file_for")
584 jmb.addSequence(pos, jmb.getSequence()[pos]);
585 File fl = new File(pe.getFile());
586 DataSourceType protocol = DataSourceType.URL;
591 protocol = DataSourceType.FILE;
593 } catch (Throwable e)
597 stopProgressBar("", startTime);
599 // Explicitly map to the filename used by Chimera ;
600 pdb = jmb.getSsm().setMapping(jmb.getSequence()[pos],
601 jmb.getChains()[pos], pe.getFile(), protocol);
602 stashFoundChains(pdb, pe.getFile());
603 } catch (OutOfMemoryError oomerror)
606 "When trying to open and map structures from Chimera!",
608 } catch (Exception ex)
610 Cache.log.error("Couldn't open " + pe.getFile()
611 + " in Chimera viewer!", ex);
614 Cache.log.debug("File locations are " + files);
620 jmb.setFinishedInit(true);
621 jmb.setLoadingFromArchive(false);
624 * ensure that any newly discovered features (e.g. RESNUM)
625 * are added to any open feature settings dialog
627 FeatureRenderer fr = getBinding().getFeatureRenderer(null);
633 // refresh the sequence colours for the new structure(s)
634 for (AlignmentPanel ap : _colourwith)
636 jmb.updateColours(ap);
638 // do superposition if asked to
639 if (Cache.getDefault("AUTOSUPERIMPOSE", true) && alignAddedStructures)
641 new Thread(new Runnable()
646 alignStructs_withAllAlignPanels();
649 alignAddedStructures = false;
651 addingStructures = false;
658 * Fetch PDB data and save to a local file. Returns the full path to the file,
659 * or null if fetch fails.
661 * @param processingEntry
666 private void stashFoundChains(StructureFile pdb, String file)
668 for (int i = 0; i < pdb.getChains().size(); i++)
670 String chid = new String(pdb.getId() + ":"
671 + pdb.getChains().elementAt(i).id);
672 jmb.getChainNames().add(chid);
673 jmb.getChainFile().put(chid, file);
676 private String fetchPdbFile(PDBEntry processingEntry) throws Exception
678 // FIXME: this is duplicated code with Jmol frame ?
679 String filePath = null;
680 Pdb pdbclient = new Pdb();
681 AlignmentI pdbseq = null;
682 String pdbid = processingEntry.getId();
683 long handle = System.currentTimeMillis()
684 + Thread.currentThread().hashCode();
687 * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
689 String msg = MessageManager.formatMessage("status.fetching_pdb",
690 new Object[] { pdbid });
691 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
692 // long hdl = startProgressBar(MessageManager.formatMessage(
693 // "status.fetching_pdb", new Object[]
697 pdbseq = pdbclient.getSequenceRecords(pdbid);
698 } catch (OutOfMemoryError oomerror)
700 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
703 msg = pdbid + " " + MessageManager.getString("label.state_completed");
704 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
705 // stopProgressBar(msg, hdl);
708 * If PDB data were saved and are not invalid (empty alignment), return the
711 if (pdbseq != null && pdbseq.getHeight() > 0)
713 // just use the file name from the first sequence's first PDBEntry
714 filePath = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
715 .elementAt(0).getFile()).getAbsolutePath();
716 processingEntry.setFile(filePath);
722 * Convenience method to update the progress bar if there is one. Be sure to
723 * call stopProgressBar with the returned handle to remove the message.
728 public long startProgressBar(String msg)
730 // TODO would rather have startProgress/stopProgress as the
731 // IProgressIndicator interface
732 long tm = random.nextLong();
733 if (progressBar != null)
735 progressBar.setProgressBar(msg, tm);
741 * End the progress bar with the specified handle, leaving a message (if not
742 * null) on the status bar
747 public void stopProgressBar(String msg, long handle)
749 if (progressBar != null)
751 progressBar.setProgressBar(msg, handle);
756 public void eps_actionPerformed(ActionEvent e)
760 .getString("error.eps_generation_not_implemented"));
764 public void png_actionPerformed(ActionEvent e)
768 .getString("error.png_generation_not_implemented"));
772 public void showHelp_actionPerformed(ActionEvent actionEvent)
777 .openURL("https://www.cgl.ucsf.edu/chimera/docs/UsersGuide");
778 } catch (IOException ex)
784 public AAStructureBindingModel getBinding()
790 * Ask Chimera to save its session to the designated file path, or to a
791 * temporary file if the path is null. Returns the file path if successful,
797 protected String saveSession(String filepath)
799 String pathUsed = filepath;
802 if (pathUsed == null)
804 File tempFile = File.createTempFile("chimera", ".py");
805 tempFile.deleteOnExit();
806 pathUsed = tempFile.getPath();
808 boolean result = jmb.saveSession(pathUsed);
811 this.chimeraSessionFile = pathUsed;
814 } catch (IOException e)
821 * Returns a string representing the state of the Chimera session. This is
822 * done by requesting Chimera to save its session to a temporary file, then
823 * reading the file contents. Returns an empty string on any error.
826 public String getStateInfo()
828 String sessionFile = saveSession(null);
829 if (sessionFile == null)
833 InputStream is = null;
836 File f = new File(sessionFile);
837 byte[] bytes = new byte[(int) f.length()];
838 is = new FileInputStream(sessionFile);
840 return new String(bytes);
841 } catch (IOException e)
851 } catch (IOException e)
860 protected void fitToWindow_actionPerformed()
866 public ViewerType getViewerType()
868 return ViewerType.CHIMERA;
872 protected String getViewerName()
878 * Sends commands to align structures according to associated alignment(s).
883 protected String alignStructs_withAllAlignPanels()
885 String reply = super.alignStructs_withAllAlignPanels();
888 statusBar.setText("Superposition failed: " + reply);