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);
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()
110 public void actionPerformed(ActionEvent e)
112 sendFeaturesToChimera();
115 viewerActionMenu.add(writeFeatures);
117 final JMenu fetchAttributes = new JMenu(
118 MessageManager.getString("label.fetch_chimera_attributes"));
119 fetchAttributes.setToolTipText(MessageManager
120 .getString("label.fetch_chimera_attributes_tip"));
121 fetchAttributes.addMouseListener(new MouseAdapter()
125 public void mouseEntered(MouseEvent e)
127 buildAttributesMenu(fetchAttributes);
130 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());
194 statusBar.setText(MessageManager.formatMessage("label.attributes_set",
199 * add a single PDB structure to a new or existing Chimera view
206 public ChimeraViewFrame(PDBEntry pdbentry, SequenceI[] seq,
207 String[] chains, final AlignmentPanel ap)
210 String pdbId = pdbentry.getId();
213 * If the PDB file is already loaded, the user may just choose to add to an
214 * existing viewer (or cancel)
216 if (addAlreadyLoadedFile(seq, chains, ap, pdbId))
222 * Check if there are other Chimera views involving this alignment and give
223 * user the option to add and align this molecule to one of them (or cancel)
225 if (addToExistingViewer(pdbentry, seq, chains, ap, pdbId))
231 * If the options above are declined or do not apply, show the structure in
234 openNewChimera(ap, new PDBEntry[] { pdbentry },
235 new SequenceI[][] { seq });
239 * Create a helper to manage progress bar display
241 protected void createProgressBar()
243 if (progressBar == null)
245 progressBar = new ProgressBar(statusPanel, statusBar);
249 private void openNewChimera(AlignmentPanel ap, PDBEntry[] pdbentrys,
253 jmb = new JalviewChimeraBindingModel(this,
254 ap.getStructureSelectionManager(), pdbentrys, seqs, null);
255 addAlignmentPanel(ap);
256 useAlignmentPanelForColourbyseq(ap);
258 if (pdbentrys.length > 1)
260 alignAddedStructures = true;
261 useAlignmentPanelForSuperposition(ap);
263 jmb.setColourBySequence(true);
264 setSize(myWidth, myHeight);
267 addingStructures = false;
268 worker = new Thread(this);
271 this.addInternalFrameListener(new InternalFrameAdapter()
274 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
283 * Create a new viewer from saved session state data including Chimera session
286 * @param chimeraSessionFile
290 * @param colourByChimera
291 * @param colourBySequence
294 public ChimeraViewFrame(String chimeraSessionFile,
295 AlignmentPanel alignPanel, PDBEntry[] pdbArray,
296 SequenceI[][] seqsArray, boolean colourByChimera,
297 boolean colourBySequence, String newViewId)
300 setViewId(newViewId);
301 this.chimeraSessionFile = chimeraSessionFile;
302 openNewChimera(alignPanel, pdbArray, seqsArray);
305 jmb.setColourBySequence(false);
306 seqColour.setSelected(false);
307 viewerColour.setSelected(true);
309 else if (colourBySequence)
311 jmb.setColourBySequence(true);
312 seqColour.setSelected(true);
313 viewerColour.setSelected(false);
318 * create a new viewer containing several structures superimposed using the
325 public ChimeraViewFrame(PDBEntry[] pe, SequenceI[][] seqs,
329 openNewChimera(ap, pe, seqs);
333 * Default constructor
335 public ChimeraViewFrame()
340 * closeViewer will decide whether or not to close this frame
341 * depending on whether user chooses to Cancel or not
343 setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
347 * Returns a list of any Chimera viewers in the desktop. The list is
348 * restricted to those linked to the given alignment panel if it is not null.
351 protected List<StructureViewerBase> getViewersFor(AlignmentPanel ap)
353 List<StructureViewerBase> result = new ArrayList<StructureViewerBase>();
354 JInternalFrame[] frames = Desktop.instance.getAllFrames();
356 for (JInternalFrame frame : frames)
358 if (frame instanceof ChimeraViewFrame)
360 if (ap == null || ((StructureViewerBase) frame).isLinkedWith(ap))
362 result.add((StructureViewerBase) frame);
370 * Launch Chimera. If we have a chimera session file name, send Chimera the
371 * command to open its saved session file.
375 jmb.setFinishedInit(false);
376 Desktop.addInternalFrame(this,
377 jmb.getViewerTitle(getViewerName(), true), getBounds().width,
380 if (!jmb.launchChimera())
382 JvOptionPane.showMessageDialog(Desktop.desktop,
383 MessageManager.getString("label.chimera_failed"),
384 MessageManager.getString("label.error_loading_file"),
385 JvOptionPane.ERROR_MESSAGE);
390 if (this.chimeraSessionFile != null)
392 boolean opened = jmb.openSession(chimeraSessionFile);
396 .println("An error occurred opening Chimera session file "
397 + chimeraSessionFile);
401 jmb.startChimeraListener();
405 * Show only the selected chain(s) in the viewer
408 void showSelectedChains()
410 List<String> toshow = new ArrayList<String>();
411 for (int i = 0; i < chainMenu.getItemCount(); i++)
413 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
415 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
416 if (item.isSelected())
418 toshow.add(item.getText());
422 jmb.showChains(toshow);
426 * Close down this instance of Jalview's Chimera viewer, giving the user the
427 * option to close the associated Chimera window (process). They may wish to
428 * keep it open until they have had an opportunity to save any work.
430 * @param closeChimera
431 * if true, close any linked Chimera process; if false, prompt first
434 public void closeViewer(boolean closeChimera)
436 if (jmb != null && jmb.isChimeraRunning())
440 String prompt = MessageManager.formatMessage(
441 "label.confirm_close_chimera",
442 new Object[] { jmb.getViewerTitle(getViewerName(),
444 prompt = JvSwingUtils.wrapTooltip(true, prompt);
445 int confirm = JvOptionPane.showConfirmDialog(this, prompt,
446 MessageManager.getString("label.close_viewer"),
447 JvOptionPane.YES_NO_CANCEL_OPTION);
449 * abort closure if user hits escape or Cancel
451 if (confirm == JvOptionPane.CANCEL_OPTION
452 || confirm == JvOptionPane.CLOSED_OPTION)
456 closeChimera = confirm == JvOptionPane.YES_OPTION;
458 jmb.closeViewer(closeChimera);
460 setAlignmentPanel(null);
464 // TODO: check for memory leaks where instance isn't finalised because jmb
465 // holds a reference to the window
471 * Open any newly added PDB structures in Chimera, having first fetched data
472 * from PDB (if not already saved).
478 // todo - record which pdbids were successfully imported.
479 StringBuilder errormsgs = new StringBuilder(128);
480 StringBuilder files = new StringBuilder(128);
481 List<PDBEntry> filePDB = new ArrayList<PDBEntry>();
482 List<Integer> filePDBpos = new ArrayList<Integer>();
483 PDBEntry thePdbEntry = null;
484 StructureFile pdb = null;
487 String[] curfiles = jmb.getStructureFiles(); // files currently in viewer
488 // TODO: replace with reference fetching/transfer code (validate PDBentry
490 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
493 thePdbEntry = jmb.getPdbEntry(pi);
494 if (thePdbEntry.getFile() == null)
497 * Retrieve PDB data, save to file, attach to PDBEntry
499 file = fetchPdbFile(thePdbEntry);
502 errormsgs.append("'" + thePdbEntry.getId() + "' ");
508 * Got file already - ignore if already loaded in Chimera.
510 file = new File(thePdbEntry.getFile()).getAbsoluteFile()
512 if (curfiles != null && curfiles.length > 0)
514 addingStructures = true; // already files loaded.
515 for (int c = 0; c < curfiles.length; c++)
517 if (curfiles[c].equals(file))
527 filePDB.add(thePdbEntry);
528 filePDBpos.add(Integer.valueOf(pi));
529 files.append(" \"" + Platform.escapeString(file) + "\"");
532 } catch (OutOfMemoryError oomerror)
534 new OOMWarning("Retrieving PDB files: " + thePdbEntry.getId(),
536 } catch (Exception ex)
538 ex.printStackTrace();
539 errormsgs.append("When retrieving pdbfiles for '"
540 + thePdbEntry.getId() + "'");
542 if (errormsgs.length() > 0)
545 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
546 .formatMessage("label.pdb_entries_couldnt_be_retrieved",
547 new Object[] { errormsgs.toString() }),
548 MessageManager.getString("label.couldnt_load_file"),
549 JvOptionPane.ERROR_MESSAGE);
552 if (files.length() > 0)
554 jmb.setFinishedInit(false);
555 if (!addingStructures)
560 } catch (Exception ex)
562 Cache.log.error("Couldn't open Chimera viewer!", ex);
566 for (PDBEntry pe : filePDB)
569 if (pe.getFile() != null)
573 int pos = filePDBpos.get(num).intValue();
574 long startTime = startProgressBar(getViewerName() + " "
575 + MessageManager.getString("status.opening_file_for")
578 jmb.addSequence(pos, jmb.getSequence()[pos]);
579 File fl = new File(pe.getFile());
580 DataSourceType protocol = DataSourceType.URL;
585 protocol = DataSourceType.FILE;
587 } catch (Throwable e)
591 stopProgressBar("", startTime);
593 // Explicitly map to the filename used by Chimera ;
594 pdb = jmb.getSsm().setMapping(jmb.getSequence()[pos],
595 jmb.getChains()[pos], pe.getFile(), protocol,
597 stashFoundChains(pdb, pe.getFile());
598 } catch (OutOfMemoryError oomerror)
601 "When trying to open and map structures from Chimera!",
603 } catch (Exception ex)
605 Cache.log.error("Couldn't open " + pe.getFile()
606 + " in Chimera viewer!", ex);
609 Cache.log.debug("File locations are " + files);
615 jmb.setFinishedInit(true);
616 jmb.setLoadingFromArchive(false);
619 * ensure that any newly discovered features (e.g. RESNUM)
620 * are added to any open feature settings dialog
622 FeatureRenderer fr = getBinding().getFeatureRenderer(null);
628 // refresh the sequence colours for the new structure(s)
629 for (AlignmentPanel ap : _colourwith)
631 jmb.updateColours(ap);
633 // do superposition if asked to
634 if (Cache.getDefault("AUTOSUPERIMPOSE", true) && alignAddedStructures)
636 new Thread(new Runnable()
641 alignStructs_withAllAlignPanels();
644 alignAddedStructures = false;
646 addingStructures = false;
653 * Fetch PDB data and save to a local file. Returns the full path to the file,
654 * or null if fetch fails. TODO: refactor to common with Jmol ? duplication
656 * @param processingEntry
661 private void stashFoundChains(StructureFile pdb, String file)
663 for (int i = 0; i < pdb.getChains().size(); i++)
665 String chid = new String(pdb.getId() + ":"
666 + pdb.getChains().elementAt(i).id);
667 jmb.getChainNames().add(chid);
668 jmb.getChainFile().put(chid, file);
671 private String fetchPdbFile(PDBEntry processingEntry) throws Exception
673 // FIXME: this is duplicated code with Jmol frame ?
674 String filePath = null;
675 Pdb pdbclient = new Pdb();
676 AlignmentI pdbseq = null;
677 String pdbid = processingEntry.getId();
678 long handle = System.currentTimeMillis()
679 + Thread.currentThread().hashCode();
682 * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
684 String msg = MessageManager.formatMessage("status.fetching_pdb",
685 new Object[] { pdbid });
686 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
687 // long hdl = startProgressBar(MessageManager.formatMessage(
688 // "status.fetching_pdb", new Object[]
692 pdbseq = pdbclient.getSequenceRecords(pdbid);
693 } catch (OutOfMemoryError oomerror)
695 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
698 msg = pdbid + " " + MessageManager.getString("label.state_completed");
699 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
700 // stopProgressBar(msg, hdl);
703 * If PDB data were saved and are not invalid (empty alignment), return the
706 if (pdbseq != null && pdbseq.getHeight() > 0)
708 // just use the file name from the first sequence's first PDBEntry
709 filePath = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
710 .elementAt(0).getFile()).getAbsolutePath();
711 processingEntry.setFile(filePath);
717 * Convenience method to update the progress bar if there is one. Be sure to
718 * call stopProgressBar with the returned handle to remove the message.
723 public long startProgressBar(String msg)
725 // TODO would rather have startProgress/stopProgress as the
726 // IProgressIndicator interface
727 long tm = random.nextLong();
728 if (progressBar != null)
730 progressBar.setProgressBar(msg, tm);
736 * End the progress bar with the specified handle, leaving a message (if not
737 * null) on the status bar
742 public void stopProgressBar(String msg, long handle)
744 if (progressBar != null)
746 progressBar.setProgressBar(msg, handle);
751 public void eps_actionPerformed(ActionEvent e)
755 .getString("error.eps_generation_not_implemented"));
759 public void png_actionPerformed(ActionEvent e)
763 .getString("error.png_generation_not_implemented"));
767 public void showHelp_actionPerformed(ActionEvent actionEvent)
772 .openURL("https://www.cgl.ucsf.edu/chimera/docs/UsersGuide");
773 } catch (IOException ex)
779 public AAStructureBindingModel getBinding()
785 * Ask Chimera to save its session to the designated file path, or to a
786 * temporary file if the path is null. Returns the file path if successful,
792 protected String saveSession(String filepath)
794 String pathUsed = filepath;
797 if (pathUsed == null)
799 File tempFile = File.createTempFile("chimera", ".py");
800 tempFile.deleteOnExit();
801 pathUsed = tempFile.getPath();
803 boolean result = jmb.saveSession(pathUsed);
806 this.chimeraSessionFile = pathUsed;
809 } catch (IOException e)
816 * Returns a string representing the state of the Chimera session. This is
817 * done by requesting Chimera to save its session to a temporary file, then
818 * reading the file contents. Returns an empty string on any error.
821 public String getStateInfo()
823 String sessionFile = saveSession(null);
824 if (sessionFile == null)
828 InputStream is = null;
831 File f = new File(sessionFile);
832 byte[] bytes = new byte[(int) f.length()];
833 is = new FileInputStream(sessionFile);
835 return new String(bytes);
836 } catch (IOException e)
846 } catch (IOException e)
855 protected void fitToWindow_actionPerformed()
861 public ViewerType getViewerType()
863 return ViewerType.CHIMERA;
867 protected String getViewerName()
873 * Sends commands to align structures according to associated alignment(s).
878 protected String alignStructs_withAllAlignPanels()
880 String reply = super.alignStructs_withAllAlignPanels();
883 statusBar.setText("Superposition failed: " + reply);
889 protected IProgressIndicator getIProgressIndicator()
895 protected AAStructureBindingModel getBindingModel()