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.ImageMaker.TYPE;
36 import jalview.util.MessageManager;
37 import jalview.util.Platform;
38 import jalview.ws.dbsources.Pdb;
40 import java.awt.event.ActionEvent;
41 import java.awt.event.ActionListener;
42 import java.awt.event.MouseAdapter;
43 import java.awt.event.MouseEvent;
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;
53 import javax.swing.JCheckBoxMenuItem;
54 import javax.swing.JInternalFrame;
55 import javax.swing.JMenu;
56 import javax.swing.JMenuItem;
57 import javax.swing.event.InternalFrameAdapter;
58 import javax.swing.event.InternalFrameEvent;
61 * GUI elements for handling an external chimera display
66 public class ChimeraViewFrame extends StructureViewerBase
68 private JalviewChimeraBinding jmb;
70 private IProgressIndicator progressBar = null;
73 * Path to Chimera session file. This is set when an open Jalview/Chimera
74 * session is saved, or on restore from a Jalview project (if it holds the
75 * filename of any saved Chimera sessions).
77 private String chimeraSessionFile = null;
79 private Random random = new Random();
81 private int myWidth = 500;
83 private int myHeight = 150;
86 * Initialise menu options.
89 protected void initMenus()
93 viewerActionMenu.setText(MessageManager.getString("label.chimera"));
96 .setText(MessageManager.getString("label.colour_with_chimera"));
97 viewerColour.setToolTipText(MessageManager
98 .getString("label.let_chimera_manage_structure_colours"));
100 helpItem.setText(MessageManager.getString("label.chimera_help"));
101 savemenu.setVisible(false); // not yet implemented
102 viewMenu.add(fitToWindow);
104 JMenuItem writeFeatures = new JMenuItem(
105 MessageManager.getString("label.create_chimera_attributes"));
106 writeFeatures.setToolTipText(MessageManager
107 .getString("label.create_chimera_attributes_tip"));
108 writeFeatures.addActionListener(new ActionListener()
111 public void actionPerformed(ActionEvent e)
113 sendFeaturesToChimera();
116 viewerActionMenu.add(writeFeatures);
118 final JMenu fetchAttributes = new JMenu(
119 MessageManager.getString("label.fetch_chimera_attributes"));
120 fetchAttributes.setToolTipText(
121 MessageManager.getString("label.fetch_chimera_attributes_tip"));
122 fetchAttributes.addMouseListener(new MouseAdapter()
126 public void mouseEntered(MouseEvent e)
128 buildAttributesMenu(fetchAttributes);
131 viewerActionMenu.add(fetchAttributes);
135 * Query Chimera for its residue attribute names and add them as items off the
138 * @param attributesMenu
140 protected void buildAttributesMenu(JMenu attributesMenu)
142 List<String> atts = jmb.sendChimeraCommand("list resattr", true);
147 attributesMenu.removeAll();
148 Collections.sort(atts);
149 for (String att : atts)
151 final String attName = att.split(" ")[1];
154 * ignore 'jv_*' attributes, as these are Jalview features that have
155 * been transferred to residue attributes in Chimera!
157 if (!attName.startsWith(ChimeraCommands.NAMESPACE_PREFIX))
159 JMenuItem menuItem = new JMenuItem(attName);
160 menuItem.addActionListener(new ActionListener()
163 public void actionPerformed(ActionEvent e)
165 getChimeraAttributes(attName);
168 attributesMenu.add(menuItem);
174 * Read residues in Chimera with the given attribute name, and set as features
175 * on the corresponding sequence positions (if any)
179 protected void getChimeraAttributes(String attName)
181 jmb.copyStructureAttributesToFeatures(attName, getAlignmentPanel());
185 * Send a command to Chimera to create residue attributes for Jalview features
187 * The syntax is: setattr r <attName> <attValue> <atomSpec>
189 * For example: setattr r jv:chain "Ferredoxin-1, Chloroplastic" #0:94.A
191 protected void sendFeaturesToChimera()
193 int count = jmb.sendFeaturesToViewer(getAlignmentPanel());
195 MessageManager.formatMessage("label.attributes_set", count));
199 * open a single PDB structure in a new Chimera view
206 public ChimeraViewFrame(PDBEntry pdbentry, SequenceI[] seq,
207 String[] chains, final AlignmentPanel ap)
211 openNewChimera(ap, new PDBEntry[] { pdbentry },
217 * Create a helper to manage progress bar display
219 protected void createProgressBar()
221 if (progressBar == null)
223 progressBar = new ProgressBar(statusPanel, statusBar);
227 private void openNewChimera(AlignmentPanel ap, PDBEntry[] pdbentrys,
231 jmb = new JalviewChimeraBindingModel(this,
232 ap.getStructureSelectionManager(), pdbentrys, seqs, null);
233 addAlignmentPanel(ap);
234 useAlignmentPanelForColourbyseq(ap);
236 if (pdbentrys.length > 1)
238 useAlignmentPanelForSuperposition(ap);
240 jmb.setColourBySequence(true);
241 setSize(myWidth, myHeight);
244 addingStructures = false;
245 worker = new Thread(this);
248 this.addInternalFrameListener(new InternalFrameAdapter()
251 public void internalFrameClosing(
252 InternalFrameEvent internalFrameEvent)
261 * Create a new viewer from saved session state data including Chimera session
264 * @param chimeraSessionFile
268 * @param colourByChimera
269 * @param colourBySequence
272 public ChimeraViewFrame(String chimeraSessionFile,
273 AlignmentPanel alignPanel, PDBEntry[] pdbArray,
274 SequenceI[][] seqsArray, boolean colourByChimera,
275 boolean colourBySequence, String newViewId)
278 setViewId(newViewId);
279 this.chimeraSessionFile = chimeraSessionFile;
280 openNewChimera(alignPanel, pdbArray, seqsArray);
283 jmb.setColourBySequence(false);
284 seqColour.setSelected(false);
285 viewerColour.setSelected(true);
287 else if (colourBySequence)
289 jmb.setColourBySequence(true);
290 seqColour.setSelected(true);
291 viewerColour.setSelected(false);
296 * create a new viewer containing several structures, optionally superimposed
297 * using the given alignPanel.
303 public ChimeraViewFrame(PDBEntry[] pe, boolean alignAdded,
308 setAlignAddedStructures(alignAdded);
309 openNewChimera(ap, pe, seqs);
313 * Default constructor
315 public ChimeraViewFrame()
320 * closeViewer will decide whether or not to close this frame
321 * depending on whether user chooses to Cancel or not
323 setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
327 * Launch Chimera. If we have a chimera session file name, send Chimera the
328 * command to open its saved session file.
332 jmb.setFinishedInit(false);
333 Desktop.addInternalFrame(this,
334 jmb.getViewerTitle(getViewerName(), true), getBounds().width,
337 if (!jmb.launchChimera())
339 JvOptionPane.showMessageDialog(Desktop.desktop,
340 MessageManager.getString("label.chimera_failed"),
341 MessageManager.getString("label.error_loading_file"),
342 JvOptionPane.ERROR_MESSAGE);
347 if (this.chimeraSessionFile != null)
349 boolean opened = jmb.openSession(chimeraSessionFile);
352 System.err.println("An error occurred opening Chimera session file "
353 + chimeraSessionFile);
357 if (!Platform.isJS())
359 jmb.startChimeraListener();
364 * Show only the selected chain(s) in the viewer
367 void showSelectedChains()
369 List<String> toshow = new ArrayList<>();
370 for (int i = 0; i < chainMenu.getItemCount(); i++)
372 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
374 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
375 if (item.isSelected())
377 toshow.add(item.getText());
381 jmb.showChains(toshow);
385 * Close down this instance of Jalview's Chimera viewer, giving the user the
386 * option to close the associated Chimera window (process). They may wish to
387 * keep it open until they have had an opportunity to save any work.
389 * @param closeChimera
390 * if true, close any linked Chimera process; if false, prompt first
393 public void closeViewer(boolean closeChimera)
395 if (jmb != null && jmb.isChimeraRunning())
399 String prompt = MessageManager
400 .formatMessage("label.confirm_close_chimera", new Object[]
401 { jmb.getViewerTitle(getViewerName(), false) });
402 prompt = JvSwingUtils.wrapTooltip(true, prompt);
403 int confirm = JvOptionPane.showConfirmDialog(this, prompt,
404 MessageManager.getString("label.close_viewer"),
405 JvOptionPane.YES_NO_CANCEL_OPTION);
407 * abort closure if user hits escape or Cancel
409 if (confirm == JvOptionPane.CANCEL_OPTION
410 || confirm == JvOptionPane.CLOSED_OPTION)
414 closeChimera = confirm == JvOptionPane.YES_OPTION;
416 jmb.closeViewer(closeChimera);
418 setAlignmentPanel(null);
422 // TODO: check for memory leaks where instance isn't finalised because jmb
423 // holds a reference to the window
429 * Open any newly added PDB structures in Chimera, having first fetched data
430 * from PDB (if not already saved).
436 // todo - record which pdbids were successfully imported.
437 StringBuilder errormsgs = new StringBuilder(128);
438 StringBuilder files = new StringBuilder(128);
439 List<PDBEntry> filePDB = new ArrayList<>();
440 List<Integer> filePDBpos = new ArrayList<>();
441 PDBEntry thePdbEntry = null;
442 StructureFile pdb = null;
445 String[] curfiles = jmb.getStructureFiles(); // files currently in viewer
446 // TODO: replace with reference fetching/transfer code (validate PDBentry
448 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
451 thePdbEntry = jmb.getPdbEntry(pi);
452 if (thePdbEntry.getFile() == null)
455 * Retrieve PDB data, save to file, attach to PDBEntry
457 file = fetchPdbFile(thePdbEntry);
460 errormsgs.append("'" + thePdbEntry.getId() + "' ");
466 * Got file already - ignore if already loaded in Chimera.
468 file = new File(thePdbEntry.getFile()).getAbsoluteFile()
470 if (curfiles != null && curfiles.length > 0)
472 addingStructures = true; // already files loaded.
473 for (int c = 0; c < curfiles.length; c++)
475 if (curfiles[c].equals(file))
485 filePDB.add(thePdbEntry);
486 filePDBpos.add(Integer.valueOf(pi));
487 files.append(" \"" + Platform.escapeString(file) + "\"");
490 } catch (OutOfMemoryError oomerror)
492 new OOMWarning("Retrieving PDB files: " + thePdbEntry.getId(),
494 } catch (Exception ex)
496 ex.printStackTrace();
498 "When retrieving pdbfiles for '" + thePdbEntry.getId() + "'");
500 if (errormsgs.length() > 0)
503 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
504 MessageManager.formatMessage(
505 "label.pdb_entries_couldnt_be_retrieved", new Object[]
506 { errormsgs.toString() }),
507 MessageManager.getString("label.couldnt_load_file"),
508 JvOptionPane.ERROR_MESSAGE);
511 if (files.length() > 0)
513 jmb.setFinishedInit(false);
514 if (!addingStructures)
519 } catch (Exception ex)
521 Cache.log.error("Couldn't open Chimera viewer!", ex);
525 for (PDBEntry pe : filePDB)
528 if (pe.getFile() != null)
532 int pos = filePDBpos.get(num).intValue();
533 long startTime = startProgressBar(getViewerName() + " "
534 + MessageManager.getString("status.opening_file_for")
537 jmb.addSequence(pos, jmb.getSequence()[pos]);
538 File fl = new File(pe.getFile());
539 DataSourceType protocol = DataSourceType.URL;
544 protocol = DataSourceType.FILE;
546 } catch (Throwable e)
550 stopProgressBar("", startTime);
552 // Explicitly map to the filename used by Chimera ;
554 pdb = jmb.getSsm().setMapping(jmb.getSequence()[pos],
555 jmb.getChains()[pos], pe.getFile(), protocol,
557 stashFoundChains(pdb, pe.getFile());
559 } catch (OutOfMemoryError oomerror)
562 "When trying to open and map structures from Chimera!",
564 } catch (Exception ex)
567 "Couldn't open " + pe.getFile() + " in Chimera viewer!",
571 Cache.log.debug("File locations are " + files);
577 jmb.setFinishedInit(true);
578 jmb.setLoadingFromArchive(false);
581 * ensure that any newly discovered features (e.g. RESNUM)
582 * are added to any open feature settings dialog
584 FeatureRenderer fr = getBinding().getFeatureRenderer(null);
590 // refresh the sequence colours for the new structure(s)
591 for (AlignmentPanel ap : _colourwith)
593 jmb.updateColours(ap);
595 // do superposition if asked to
596 if (alignAddedStructures)
598 new Thread(new Runnable()
603 alignStructs_withAllAlignPanels();
607 addingStructures = false;
614 * Fetch PDB data and save to a local file. Returns the full path to the file,
615 * or null if fetch fails. TODO: refactor to common with Jmol ? duplication
617 * @param processingEntry
622 private void stashFoundChains(StructureFile pdb, String file)
624 for (int i = 0; i < pdb.getChains().size(); i++)
626 String chid = new String(
627 pdb.getId() + ":" + pdb.getChains().elementAt(i).id);
628 jmb.getChainNames().add(chid);
629 jmb.getChainFile().put(chid, file);
633 private String fetchPdbFile(PDBEntry processingEntry) throws Exception
635 String filePath = null;
636 Pdb pdbclient = new Pdb();
637 AlignmentI pdbseq = null;
638 String pdbid = processingEntry.getId();
639 long handle = System.currentTimeMillis()
640 + Thread.currentThread().hashCode();
643 * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
645 String msg = MessageManager.formatMessage("status.fetching_pdb",
648 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
649 // long hdl = startProgressBar(MessageManager.formatMessage(
650 // "status.fetching_pdb", new Object[]
654 pdbseq = pdbclient.getSequenceRecords(pdbid);
655 } catch (OutOfMemoryError oomerror)
657 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
660 msg = pdbid + " " + MessageManager.getString("label.state_completed");
661 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
662 // stopProgressBar(msg, hdl);
665 * If PDB data were saved and are not invalid (empty alignment), return the
668 if (pdbseq != null && pdbseq.getHeight() > 0)
670 // just use the file name from the first sequence's first PDBEntry
671 filePath = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
672 .elementAt(0).getFile()).getAbsolutePath();
673 processingEntry.setFile(filePath);
679 * Convenience method to update the progress bar if there is one. Be sure to
680 * call stopProgressBar with the returned handle to remove the message.
685 public long startProgressBar(String msg)
687 // TODO would rather have startProgress/stopProgress as the
688 // IProgressIndicator interface
689 long tm = random.nextLong();
690 if (progressBar != null)
692 progressBar.setProgressBar(msg, tm);
698 * End the progress bar with the specified handle, leaving a message (if not
699 * null) on the status bar
704 public void stopProgressBar(String msg, long handle)
706 if (progressBar != null)
708 progressBar.setProgressBar(msg, handle);
713 public void makePDBImage(TYPE imageType)
715 throw new UnsupportedOperationException(
716 "Image export for Chimera is not implemented");
720 public void showHelp_actionPerformed(ActionEvent actionEvent)
725 .openURL("https://www.cgl.ucsf.edu/chimera/docs/UsersGuide");
726 } catch (IOException ex)
732 public AAStructureBindingModel getBinding()
738 * Ask Chimera to save its session to the designated file path, or to a
739 * temporary file if the path is null. Returns the file path if successful,
745 protected String saveSession(String filepath)
747 String pathUsed = filepath;
750 if (pathUsed == null)
752 File tempFile = File.createTempFile("chimera", ".py");
753 tempFile.deleteOnExit();
754 pathUsed = tempFile.getPath();
756 boolean result = jmb.saveSession(pathUsed);
759 this.chimeraSessionFile = pathUsed;
762 } catch (IOException e)
769 * Returns a string representing the state of the Chimera session. This is
770 * done by requesting Chimera to save its session to a temporary file, then
771 * reading the file contents. Returns an empty string on any error.
774 public String getStateInfo()
776 String sessionFile = saveSession(null);
777 if (sessionFile == null)
781 InputStream is = null;
784 File f = new File(sessionFile);
785 byte[] bytes = new byte[(int) f.length()];
786 is = new FileInputStream(sessionFile);
788 return new String(bytes);
789 } catch (IOException e)
799 } catch (IOException e)
808 protected void fitToWindow_actionPerformed()
814 public ViewerType getViewerType()
816 return ViewerType.CHIMERA;
820 protected String getViewerName()
826 * Sends commands to align structures according to associated alignment(s).
831 protected String alignStructs_withAllAlignPanels()
833 String reply = super.alignStructs_withAllAlignPanels();
836 statusBar.setText("Superposition failed: " + reply);
842 protected IProgressIndicator getIProgressIndicator()