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.getPdbFile(); // 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);
596 stashFoundChains(pdb, pe.getFile());
597 } catch (OutOfMemoryError oomerror)
600 "When trying to open and map structures from Chimera!",
602 } catch (Exception ex)
604 Cache.log.error("Couldn't open " + pe.getFile()
605 + " in Chimera viewer!", ex);
608 Cache.log.debug("File locations are " + files);
614 jmb.setFinishedInit(true);
615 jmb.setLoadingFromArchive(false);
618 * ensure that any newly discovered features (e.g. RESNUM)
619 * are added to any open feature settings dialog
621 FeatureRenderer fr = getBinding().getFeatureRenderer(null);
627 // refresh the sequence colours for the new structure(s)
628 for (AlignmentPanel ap : _colourwith)
630 jmb.updateColours(ap);
632 // do superposition if asked to
633 if (Cache.getDefault("AUTOSUPERIMPOSE", true) && alignAddedStructures)
635 new Thread(new Runnable()
640 alignStructs_withAllAlignPanels();
643 alignAddedStructures = false;
645 addingStructures = false;
652 * Fetch PDB data and save to a local file. Returns the full path to the file,
653 * or null if fetch fails.
655 * @param processingEntry
660 private void stashFoundChains(StructureFile pdb, String file)
662 for (int i = 0; i < pdb.getChains().size(); i++)
664 String chid = new String(pdb.getId() + ":"
665 + pdb.getChains().elementAt(i).id);
666 jmb.getChainNames().add(chid);
667 jmb.getChainFile().put(chid, file);
670 private String fetchPdbFile(PDBEntry processingEntry) throws Exception
672 // FIXME: this is duplicated code with Jmol frame ?
673 String filePath = null;
674 Pdb pdbclient = new Pdb();
675 AlignmentI pdbseq = null;
676 String pdbid = processingEntry.getId();
677 long handle = System.currentTimeMillis()
678 + Thread.currentThread().hashCode();
681 * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
683 String msg = MessageManager.formatMessage("status.fetching_pdb",
684 new Object[] { pdbid });
685 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
686 // long hdl = startProgressBar(MessageManager.formatMessage(
687 // "status.fetching_pdb", new Object[]
691 pdbseq = pdbclient.getSequenceRecords(pdbid);
692 } catch (OutOfMemoryError oomerror)
694 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
697 msg = pdbid + " " + MessageManager.getString("label.state_completed");
698 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
699 // stopProgressBar(msg, hdl);
702 * If PDB data were saved and are not invalid (empty alignment), return the
705 if (pdbseq != null && pdbseq.getHeight() > 0)
707 // just use the file name from the first sequence's first PDBEntry
708 filePath = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
709 .elementAt(0).getFile()).getAbsolutePath();
710 processingEntry.setFile(filePath);
716 * Convenience method to update the progress bar if there is one. Be sure to
717 * call stopProgressBar with the returned handle to remove the message.
722 public long startProgressBar(String msg)
724 // TODO would rather have startProgress/stopProgress as the
725 // IProgressIndicator interface
726 long tm = random.nextLong();
727 if (progressBar != null)
729 progressBar.setProgressBar(msg, tm);
735 * End the progress bar with the specified handle, leaving a message (if not
736 * null) on the status bar
741 public void stopProgressBar(String msg, long handle)
743 if (progressBar != null)
745 progressBar.setProgressBar(msg, handle);
750 public void eps_actionPerformed(ActionEvent e)
754 .getString("error.eps_generation_not_implemented"));
758 public void png_actionPerformed(ActionEvent e)
762 .getString("error.png_generation_not_implemented"));
766 public void showHelp_actionPerformed(ActionEvent actionEvent)
771 .openURL("https://www.cgl.ucsf.edu/chimera/docs/UsersGuide");
772 } catch (IOException ex)
778 public AAStructureBindingModel getBinding()
784 * Ask Chimera to save its session to the designated file path, or to a
785 * temporary file if the path is null. Returns the file path if successful,
791 protected String saveSession(String filepath)
793 String pathUsed = filepath;
796 if (pathUsed == null)
798 File tempFile = File.createTempFile("chimera", ".py");
799 tempFile.deleteOnExit();
800 pathUsed = tempFile.getPath();
802 boolean result = jmb.saveSession(pathUsed);
805 this.chimeraSessionFile = pathUsed;
808 } catch (IOException e)
815 * Returns a string representing the state of the Chimera session. This is
816 * done by requesting Chimera to save its session to a temporary file, then
817 * reading the file contents. Returns an empty string on any error.
820 public String getStateInfo()
822 String sessionFile = saveSession(null);
823 if (sessionFile == null)
827 InputStream is = null;
830 File f = new File(sessionFile);
831 byte[] bytes = new byte[(int) f.length()];
832 is = new FileInputStream(sessionFile);
834 return new String(bytes);
835 } catch (IOException e)
845 } catch (IOException e)
854 protected void fitToWindow_actionPerformed()
860 public ViewerType getViewerType()
862 return ViewerType.CHIMERA;
866 protected String getViewerName()
872 * Sends commands to align structures according to associated alignment(s).
877 protected String alignStructs_withAllAlignPanels()
879 String reply = super.alignStructs_withAllAlignPanels();
882 statusBar.setText("Superposition failed: " + reply);