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"));
95 .setText(MessageManager.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());
201 MessageManager.formatMessage("label.attributes_set", count));
205 * open a single PDB structure in a new Chimera view
212 public ChimeraViewFrame(PDBEntry pdbentry, SequenceI[] seq,
213 String[] chains, final AlignmentPanel ap)
217 openNewChimera(ap, new PDBEntry[] { pdbentry },
223 * Create a helper to manage progress bar display
225 protected void createProgressBar()
227 if (progressBar == null)
229 progressBar = new ProgressBar(statusPanel, statusBar);
233 private void openNewChimera(AlignmentPanel ap, PDBEntry[] pdbentrys,
237 jmb = new JalviewChimeraBindingModel(this,
238 ap.getStructureSelectionManager(), pdbentrys, seqs, null);
239 addAlignmentPanel(ap);
240 useAlignmentPanelForColourbyseq(ap);
242 if (pdbentrys.length > 1)
244 useAlignmentPanelForSuperposition(ap);
246 jmb.setColourBySequence(true);
247 setSize(myWidth, myHeight);
250 addingStructures = false;
251 worker = new Thread(this);
254 this.addInternalFrameListener(new InternalFrameAdapter()
257 public void internalFrameClosing(
258 InternalFrameEvent internalFrameEvent)
267 * Create a new viewer from saved session state data including Chimera session
270 * @param chimeraSessionFile
274 * @param colourByChimera
275 * @param colourBySequence
278 public ChimeraViewFrame(String chimeraSessionFile,
279 AlignmentPanel alignPanel, PDBEntry[] pdbArray,
280 SequenceI[][] seqsArray, boolean colourByChimera,
281 boolean colourBySequence, String newViewId)
284 setViewId(newViewId);
285 this.chimeraSessionFile = chimeraSessionFile;
286 openNewChimera(alignPanel, pdbArray, seqsArray);
289 jmb.setColourBySequence(false);
290 seqColour.setSelected(false);
291 viewerColour.setSelected(true);
293 else if (colourBySequence)
295 jmb.setColourBySequence(true);
296 seqColour.setSelected(true);
297 viewerColour.setSelected(false);
302 * create a new viewer containing several structures, optionally superimposed
303 * using the given alignPanel.
309 public ChimeraViewFrame(PDBEntry[] pe, boolean alignAdded,
314 setAlignAddedStructures(alignAdded);
315 openNewChimera(ap, pe, seqs);
319 * Default constructor
321 public ChimeraViewFrame()
326 * closeViewer will decide whether or not to close this frame
327 * depending on whether user chooses to Cancel or not
329 setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
333 * Launch Chimera. If we have a chimera session file name, send Chimera the
334 * command to open its saved session file.
338 jmb.setFinishedInit(false);
339 Desktop.addInternalFrame(this,
340 jmb.getViewerTitle(getViewerName(), true), getBounds().width,
343 if (!jmb.launchChimera())
345 JvOptionPane.showMessageDialog(Desktop.desktop,
346 MessageManager.getString("label.chimera_failed"),
347 MessageManager.getString("label.error_loading_file"),
348 JvOptionPane.ERROR_MESSAGE);
353 if (this.chimeraSessionFile != null)
355 boolean opened = jmb.openSession(chimeraSessionFile);
358 System.err.println("An error occurred opening Chimera session file "
359 + chimeraSessionFile);
363 jmb.startChimeraListener();
367 * Show only the selected chain(s) in the viewer
370 void showSelectedChains()
372 List<String> toshow = new ArrayList<>();
373 for (int i = 0; i < chainMenu.getItemCount(); i++)
375 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
377 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
378 if (item.isSelected())
380 toshow.add(item.getText());
384 jmb.showChains(toshow);
388 * Close down this instance of Jalview's Chimera viewer, giving the user the
389 * option to close the associated Chimera window (process). They may wish to
390 * keep it open until they have had an opportunity to save any work.
392 * @param closeChimera
393 * if true, close any linked Chimera process; if false, prompt first
396 public void closeViewer(boolean closeChimera)
398 if (jmb != null && jmb.isChimeraRunning())
402 String prompt = MessageManager
403 .formatMessage("label.confirm_close_chimera", new Object[]
404 { jmb.getViewerTitle(getViewerName(), false) });
405 prompt = JvSwingUtils.wrapTooltip(true, prompt);
406 int confirm = JvOptionPane.showConfirmDialog(this, prompt,
407 MessageManager.getString("label.close_viewer"),
408 JvOptionPane.YES_NO_CANCEL_OPTION);
410 * abort closure if user hits escape or Cancel
412 if (confirm == JvOptionPane.CANCEL_OPTION
413 || confirm == JvOptionPane.CLOSED_OPTION)
417 closeChimera = confirm == JvOptionPane.YES_OPTION;
419 jmb.closeViewer(closeChimera);
421 setAlignmentPanel(null);
425 // TODO: check for memory leaks where instance isn't finalised because jmb
426 // holds a reference to the window
432 * Open any newly added PDB structures in Chimera, having first fetched data
433 * from PDB (if not already saved).
439 // todo - record which pdbids were successfully imported.
440 StringBuilder errormsgs = new StringBuilder(128);
441 StringBuilder files = new StringBuilder(128);
442 List<PDBEntry> filePDB = new ArrayList<>();
443 List<Integer> filePDBpos = new ArrayList<>();
444 PDBEntry thePdbEntry = null;
445 StructureFile pdb = null;
448 String[] curfiles = jmb.getStructureFiles(); // files currently in viewer
449 // TODO: replace with reference fetching/transfer code (validate PDBentry
451 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
454 thePdbEntry = jmb.getPdbEntry(pi);
455 if (thePdbEntry.getFile() == null)
458 * Retrieve PDB data, save to file, attach to PDBEntry
460 file = fetchPdbFile(thePdbEntry);
463 errormsgs.append("'" + thePdbEntry.getId() + "' ");
469 * Got file already - ignore if already loaded in Chimera.
471 file = new File(thePdbEntry.getFile()).getAbsoluteFile()
473 if (curfiles != null && curfiles.length > 0)
475 addingStructures = true; // already files loaded.
476 for (int c = 0; c < curfiles.length; c++)
478 if (curfiles[c].equals(file))
488 filePDB.add(thePdbEntry);
489 filePDBpos.add(Integer.valueOf(pi));
490 files.append(" \"" + Platform.escapeString(file) + "\"");
493 } catch (OutOfMemoryError oomerror)
495 new OOMWarning("Retrieving PDB files: " + thePdbEntry.getId(),
497 } catch (Exception ex)
499 ex.printStackTrace();
501 "When retrieving pdbfiles for '" + thePdbEntry.getId() + "'");
503 if (errormsgs.length() > 0)
506 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
507 MessageManager.formatMessage(
508 "label.pdb_entries_couldnt_be_retrieved", new Object[]
509 { errormsgs.toString() }),
510 MessageManager.getString("label.couldnt_load_file"),
511 JvOptionPane.ERROR_MESSAGE);
514 if (files.length() > 0)
516 jmb.setFinishedInit(false);
517 if (!addingStructures)
522 } catch (Exception ex)
524 Cache.log.error("Couldn't open Chimera viewer!", ex);
528 for (PDBEntry pe : filePDB)
531 if (pe.getFile() != null)
535 int pos = filePDBpos.get(num).intValue();
536 long startTime = startProgressBar(getViewerName() + " "
537 + MessageManager.getString("status.opening_file_for")
540 jmb.addSequence(pos, jmb.getSequence()[pos]);
541 File fl = new File(pe.getFile());
542 DataSourceType protocol = DataSourceType.URL;
547 protocol = DataSourceType.FILE;
549 } catch (Throwable e)
553 stopProgressBar("", startTime);
555 // Explicitly map to the filename used by Chimera ;
557 pdb = jmb.getSsm().setMapping(jmb.getSequence()[pos],
558 jmb.getChains()[pos], pe.getFile(), protocol,
560 stashFoundChains(pdb, pe.getFile());
562 } catch (OutOfMemoryError oomerror)
565 "When trying to open and map structures from Chimera!",
567 } catch (Exception ex)
570 "Couldn't open " + pe.getFile() + " in Chimera viewer!",
574 Cache.log.debug("File locations are " + files);
580 jmb.setFinishedInit(true);
581 jmb.setLoadingFromArchive(false);
584 * ensure that any newly discovered features (e.g. RESNUM)
585 * are added to any open feature settings dialog
587 FeatureRenderer fr = getBinding().getFeatureRenderer(null);
593 // refresh the sequence colours for the new structure(s)
594 for (AlignmentPanel ap : _colourwith)
596 jmb.updateColours(ap);
598 // do superposition if asked to
599 if (alignAddedStructures)
601 new Thread(new Runnable()
606 alignStructs_withAllAlignPanels();
610 addingStructures = false;
617 * Fetch PDB data and save to a local file. Returns the full path to the file,
618 * or null if fetch fails. TODO: refactor to common with Jmol ? duplication
620 * @param processingEntry
625 private void stashFoundChains(StructureFile pdb, String file)
627 for (int i = 0; i < pdb.getChains().size(); i++)
629 String chid = new String(
630 pdb.getId() + ":" + pdb.getChains().elementAt(i).id);
631 jmb.getChainNames().add(chid);
632 jmb.getChainFile().put(chid, file);
636 private String fetchPdbFile(PDBEntry processingEntry) throws Exception
638 String filePath = null;
639 Pdb pdbclient = new Pdb();
640 AlignmentI pdbseq = null;
641 String pdbid = processingEntry.getId();
642 long handle = System.currentTimeMillis()
643 + Thread.currentThread().hashCode();
646 * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
648 String msg = MessageManager.formatMessage("status.fetching_pdb",
651 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
652 // long hdl = startProgressBar(MessageManager.formatMessage(
653 // "status.fetching_pdb", new Object[]
657 pdbseq = pdbclient.getSequenceRecords(pdbid);
658 } catch (OutOfMemoryError oomerror)
660 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
663 msg = pdbid + " " + MessageManager.getString("label.state_completed");
664 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
665 // stopProgressBar(msg, hdl);
668 * If PDB data were saved and are not invalid (empty alignment), return the
671 if (pdbseq != null && pdbseq.getHeight() > 0)
673 // just use the file name from the first sequence's first PDBEntry
674 filePath = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
675 .elementAt(0).getFile()).getAbsolutePath();
676 processingEntry.setFile(filePath);
682 * Convenience method to update the progress bar if there is one. Be sure to
683 * call stopProgressBar with the returned handle to remove the message.
688 public long startProgressBar(String msg)
690 // TODO would rather have startProgress/stopProgress as the
691 // IProgressIndicator interface
692 long tm = random.nextLong();
693 if (progressBar != null)
695 progressBar.setProgressBar(msg, tm);
701 * End the progress bar with the specified handle, leaving a message (if not
702 * null) on the status bar
707 public void stopProgressBar(String msg, long handle)
709 if (progressBar != null)
711 progressBar.setProgressBar(msg, handle);
716 public void eps_actionPerformed(ActionEvent e)
718 throw new Error(MessageManager
719 .getString("error.eps_generation_not_implemented"));
723 public void png_actionPerformed(ActionEvent e)
725 throw new Error(MessageManager
726 .getString("error.png_generation_not_implemented"));
730 public void showHelp_actionPerformed(ActionEvent actionEvent)
735 .openURL("https://www.cgl.ucsf.edu/chimera/docs/UsersGuide");
736 } catch (IOException ex)
742 public AAStructureBindingModel getBinding()
748 * Ask Chimera to save its session to the designated file path, or to a
749 * temporary file if the path is null. Returns the file path if successful,
755 protected String saveSession(String filepath)
757 String pathUsed = filepath;
760 if (pathUsed == null)
762 File tempFile = File.createTempFile("chimera", ".py");
763 tempFile.deleteOnExit();
764 pathUsed = tempFile.getPath();
766 boolean result = jmb.saveSession(pathUsed);
769 this.chimeraSessionFile = pathUsed;
772 } catch (IOException e)
779 * Returns a string representing the state of the Chimera session. This is
780 * done by requesting Chimera to save its session to a temporary file, then
781 * reading the file contents. Returns an empty string on any error.
784 public String getStateInfo()
786 String sessionFile = saveSession(null);
787 if (sessionFile == null)
791 InputStream is = null;
794 File f = new File(sessionFile);
795 byte[] bytes = new byte[(int) f.length()];
796 is = new FileInputStream(sessionFile);
798 return new String(bytes);
799 } catch (IOException e)
809 } catch (IOException e)
818 protected void fitToWindow_actionPerformed()
824 public ViewerType getViewerType()
826 return ViewerType.CHIMERA;
830 protected String getViewerName()
836 * Sends commands to align structures according to associated alignment(s).
841 protected String alignStructs_withAllAlignPanels()
843 String reply = super.alignStructs_withAllAlignPanels();
846 statusBar.setText("Superposition failed: " + reply);
852 protected IProgressIndicator getIProgressIndicator()