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.AlignmentViewPanel;
24 import jalview.api.FeatureRenderer;
25 import jalview.bin.Cache;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.SequenceI;
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;
51 import javax.swing.JInternalFrame;
52 import javax.swing.JMenu;
53 import javax.swing.JMenuItem;
54 import javax.swing.event.InternalFrameAdapter;
55 import javax.swing.event.InternalFrameEvent;
58 * GUI elements for handling an external chimera display
63 public class ChimeraViewFrame extends StructureViewerBase
65 private JalviewChimeraBinding jmb;
68 * Path to Chimera session file. This is set when an open Jalview/Chimera
69 * session is saved, or on restore from a Jalview project (if it holds the
70 * filename of any saved Chimera sessions).
72 private String chimeraSessionFile = null;
74 private int myWidth = 500;
76 private int myHeight = 150;
79 * Initialise menu options.
82 protected void initMenus()
86 viewerActionMenu.setText(MessageManager.getString("label.chimera"));
89 .setText(MessageManager.getString("label.colour_with_chimera"));
90 viewerColour.setToolTipText(MessageManager
91 .getString("label.let_chimera_manage_structure_colours"));
93 helpItem.setText(MessageManager.getString("label.chimera_help"));
94 savemenu.setVisible(false); // not yet implemented
95 viewMenu.add(fitToWindow);
97 JMenuItem writeFeatures = new JMenuItem(
98 MessageManager.getString("label.create_chimera_attributes"));
99 writeFeatures.setToolTipText(MessageManager
100 .getString("label.create_chimera_attributes_tip"));
101 writeFeatures.addActionListener(new ActionListener()
104 public void actionPerformed(ActionEvent e)
106 sendFeaturesToChimera();
109 viewerActionMenu.add(writeFeatures);
111 final JMenu fetchAttributes = new JMenu(
112 MessageManager.getString("label.fetch_chimera_attributes"));
113 fetchAttributes.setToolTipText(
114 MessageManager.getString("label.fetch_chimera_attributes_tip"));
115 fetchAttributes.addMouseListener(new MouseAdapter()
119 public void mouseEntered(MouseEvent e)
121 buildAttributesMenu(fetchAttributes);
124 viewerActionMenu.add(fetchAttributes);
128 * Query Chimera for its residue attribute names and add them as items off the
131 * @param attributesMenu
133 protected void buildAttributesMenu(JMenu attributesMenu)
135 List<String> atts = jmb.getChimeraAttributes();
136 attributesMenu.removeAll();
137 Collections.sort(atts);
138 for (String attName : atts)
140 JMenuItem menuItem = new JMenuItem(attName);
141 menuItem.addActionListener(new ActionListener()
144 public void actionPerformed(ActionEvent e)
146 getChimeraAttributes(attName);
149 attributesMenu.add(menuItem);
154 * Read residues in Chimera with the given attribute name, and set as features
155 * on the corresponding sequence positions (if any)
159 protected void getChimeraAttributes(String attName)
161 jmb.copyStructureAttributesToFeatures(attName, getAlignmentPanel());
165 * Send a command to Chimera to create residue attributes for Jalview features
167 * The syntax is: setattr r <attName> <attValue> <atomSpec>
169 * For example: setattr r jv_chain "Ferredoxin-1, Chloroplastic" #0:94.A
171 protected void sendFeaturesToChimera()
173 int count = jmb.sendFeaturesToViewer(getAlignmentPanel());
175 MessageManager.formatMessage("label.attributes_set", count));
179 * open a single PDB structure in a new Chimera view
186 public ChimeraViewFrame(PDBEntry pdbentry, SequenceI[] seq,
187 String[] chains, final AlignmentPanel ap)
191 openNewChimera(ap, new PDBEntry[] { pdbentry },
197 * Create a helper to manage progress bar display
199 protected void createProgressBar()
201 if (getProgressIndicator() == null)
203 setProgressIndicator(new ProgressBar(statusPanel, statusBar));
207 private void openNewChimera(AlignmentPanel ap, PDBEntry[] pdbentrys,
211 jmb = newBindingModel(ap, pdbentrys, seqs);
212 addAlignmentPanel(ap);
213 useAlignmentPanelForColourbyseq(ap);
215 if (pdbentrys.length > 1)
217 useAlignmentPanelForSuperposition(ap);
219 jmb.setColourBySequence(true);
220 setSize(myWidth, myHeight);
223 addingStructures = false;
224 worker = new Thread(this);
227 this.addInternalFrameListener(new InternalFrameAdapter()
230 public void internalFrameClosing(
231 InternalFrameEvent internalFrameEvent)
239 protected JalviewChimeraBindingModel newBindingModel(AlignmentPanel ap,
240 PDBEntry[] pdbentrys, SequenceI[][] seqs)
242 return new JalviewChimeraBindingModel(this,
243 ap.getStructureSelectionManager(), pdbentrys, seqs, null);
247 * Create a new viewer from saved session state data including Chimera session
250 * @param chimeraSessionFile
254 * @param colourByChimera
255 * @param colourBySequence
258 public ChimeraViewFrame(String chimeraSessionFile,
259 AlignmentPanel alignPanel, PDBEntry[] pdbArray,
260 SequenceI[][] seqsArray, boolean colourByChimera,
261 boolean colourBySequence, String newViewId)
264 setViewId(newViewId);
265 this.chimeraSessionFile = chimeraSessionFile;
266 openNewChimera(alignPanel, pdbArray, seqsArray);
269 jmb.setColourBySequence(false);
270 seqColour.setSelected(false);
271 viewerColour.setSelected(true);
273 else if (colourBySequence)
275 jmb.setColourBySequence(true);
276 seqColour.setSelected(true);
277 viewerColour.setSelected(false);
282 * create a new viewer containing several structures, optionally superimposed
283 * using the given alignPanel.
289 public ChimeraViewFrame(PDBEntry[] pe, boolean alignAdded,
294 setAlignAddedStructures(alignAdded);
295 openNewChimera(ap, pe, seqs);
299 * Default constructor
301 public ChimeraViewFrame()
306 * closeViewer will decide whether or not to close this frame
307 * depending on whether user chooses to Cancel or not
309 setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
313 * Launch Chimera. If we have a chimera session file name, send Chimera the
314 * command to open its saved session file.
318 jmb.setFinishedInit(false);
319 Desktop.addInternalFrame(this,
320 jmb.getViewerTitle(getViewerName(), true), getBounds().width,
323 if (!jmb.launchChimera())
325 JvOptionPane.showMessageDialog(Desktop.desktop,
326 MessageManager.getString("label.chimera_failed"),
327 MessageManager.getString("label.error_loading_file"),
328 JvOptionPane.ERROR_MESSAGE);
333 if (this.chimeraSessionFile != null)
335 boolean opened = jmb.openSession(chimeraSessionFile);
338 System.err.println("An error occurred opening Chimera session file "
339 + chimeraSessionFile);
343 jmb.startChimeraListener();
347 * Close down this instance of Jalview's Chimera viewer, giving the user the
348 * option to close the associated Chimera window (process). They may wish to
349 * keep it open until they have had an opportunity to save any work.
351 * @param closeChimera
352 * if true, close any linked Chimera process; if false, prompt first
355 public void closeViewer(boolean closeChimera)
357 if (jmb != null && jmb.isChimeraRunning())
361 String prompt = MessageManager
362 .formatMessage("label.confirm_close_chimera", new Object[]
363 { jmb.getViewerTitle(getViewerName(), false) });
364 prompt = JvSwingUtils.wrapTooltip(true, prompt);
365 int confirm = JvOptionPane.showConfirmDialog(this, prompt,
366 MessageManager.getString("label.close_viewer"),
367 JvOptionPane.YES_NO_CANCEL_OPTION);
369 * abort closure if user hits escape or Cancel
371 if (confirm == JvOptionPane.CANCEL_OPTION
372 || confirm == JvOptionPane.CLOSED_OPTION)
376 closeChimera = confirm == JvOptionPane.YES_OPTION;
378 jmb.closeViewer(closeChimera);
380 setAlignmentPanel(null);
384 // TODO: check for memory leaks where instance isn't finalised because jmb
385 // holds a reference to the window
391 * Open any newly added PDB structures in Chimera, having first fetched data
392 * from PDB (if not already saved).
398 // todo - record which pdbids were successfully imported.
399 StringBuilder errormsgs = new StringBuilder(128);
400 StringBuilder files = new StringBuilder(128);
401 List<PDBEntry> filePDB = new ArrayList<>();
402 List<Integer> filePDBpos = new ArrayList<>();
403 PDBEntry thePdbEntry = null;
404 StructureFile pdb = null;
407 String[] curfiles = jmb.getStructureFiles(); // files currently in viewer
408 // TODO: replace with reference fetching/transfer code (validate PDBentry
410 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
413 thePdbEntry = jmb.getPdbEntry(pi);
414 if (thePdbEntry.getFile() == null)
417 * Retrieve PDB data, save to file, attach to PDBEntry
419 file = fetchPdbFile(thePdbEntry);
422 errormsgs.append("'" + thePdbEntry.getId() + "' ");
428 * Got file already - ignore if already loaded in Chimera.
430 file = new File(thePdbEntry.getFile()).getAbsoluteFile()
432 if (curfiles != null && curfiles.length > 0)
434 addingStructures = true; // already files loaded.
435 for (int c = 0; c < curfiles.length; c++)
437 if (curfiles[c].equals(file))
447 filePDB.add(thePdbEntry);
448 filePDBpos.add(Integer.valueOf(pi));
449 files.append(" \"" + Platform.escapeBackslashes(file) + "\"");
452 } catch (OutOfMemoryError oomerror)
454 new OOMWarning("Retrieving PDB files: " + thePdbEntry.getId(),
456 } catch (Exception ex)
458 ex.printStackTrace();
460 "When retrieving pdbfiles for '" + thePdbEntry.getId() + "'");
462 if (errormsgs.length() > 0)
465 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
466 MessageManager.formatMessage(
467 "label.pdb_entries_couldnt_be_retrieved", new Object[]
468 { errormsgs.toString() }),
469 MessageManager.getString("label.couldnt_load_file"),
470 JvOptionPane.ERROR_MESSAGE);
473 if (files.length() > 0)
475 jmb.setFinishedInit(false);
476 if (!addingStructures)
481 } catch (Exception ex)
483 Cache.log.error("Couldn't open Chimera viewer!", ex);
487 for (PDBEntry pe : filePDB)
490 if (pe.getFile() != null)
494 int pos = filePDBpos.get(num).intValue();
495 long startTime = startProgressBar(getViewerName() + " "
496 + MessageManager.getString("status.opening_file_for")
499 jmb.addSequence(pos, jmb.getSequence()[pos]);
500 File fl = new File(pe.getFile());
501 DataSourceType protocol = DataSourceType.URL;
506 protocol = DataSourceType.FILE;
508 } catch (Throwable e)
512 stopProgressBar("", startTime);
514 // Explicitly map to the filename used by Chimera ;
516 pdb = jmb.getSsm().setMapping(jmb.getSequence()[pos],
517 jmb.getChains()[pos], pe.getFile(), protocol,
518 getProgressIndicator());
519 stashFoundChains(pdb, pe.getFile());
521 } catch (OutOfMemoryError oomerror)
524 "When trying to open and map structures from Chimera!",
526 } catch (Exception ex)
529 "Couldn't open " + pe.getFile() + " in Chimera viewer!",
533 Cache.log.debug("File locations are " + files);
539 jmb.setFinishedInit(true);
540 jmb.setLoadingFromArchive(false);
543 * ensure that any newly discovered features (e.g. RESNUM)
544 * are added to any open feature settings dialog
546 FeatureRenderer fr = getBinding().getFeatureRenderer(null);
552 // refresh the sequence colours for the new structure(s)
553 for (AlignmentViewPanel ap : _colourwith)
555 jmb.updateColours(ap);
557 // do superposition if asked to
558 if (alignAddedStructures)
560 new Thread(new Runnable()
565 alignStructsWithAllAlignPanels();
569 addingStructures = false;
576 * Fetch PDB data and save to a local file. Returns the full path to the file,
577 * or null if fetch fails. TODO: refactor to common with Jmol ? duplication
579 * @param processingEntry
584 private void stashFoundChains(StructureFile pdb, String file)
586 for (int i = 0; i < pdb.getChains().size(); i++)
588 String chid = new String(
589 pdb.getId() + ":" + pdb.getChains().elementAt(i).id);
590 jmb.getChainNames().add(chid);
591 jmb.addChainFile(chid, file);
595 private String fetchPdbFile(PDBEntry processingEntry) throws Exception
597 String filePath = null;
598 Pdb pdbclient = new Pdb();
599 AlignmentI pdbseq = null;
600 String pdbid = processingEntry.getId();
601 long handle = System.currentTimeMillis()
602 + Thread.currentThread().hashCode();
605 * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
607 String msg = MessageManager.formatMessage("status.fetching_pdb",
610 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
611 // long hdl = startProgressBar(MessageManager.formatMessage(
612 // "status.fetching_pdb", new Object[]
616 pdbseq = pdbclient.getSequenceRecords(pdbid);
617 } catch (OutOfMemoryError oomerror)
619 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
622 msg = pdbid + " " + MessageManager.getString("label.state_completed");
623 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
624 // stopProgressBar(msg, hdl);
627 * If PDB data were saved and are not invalid (empty alignment), return the
630 if (pdbseq != null && pdbseq.getHeight() > 0)
632 // just use the file name from the first sequence's first PDBEntry
633 filePath = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
634 .elementAt(0).getFile()).getAbsolutePath();
635 processingEntry.setFile(filePath);
641 public void eps_actionPerformed()
643 throw new Error(MessageManager
644 .getString("error.eps_generation_not_implemented"));
648 public void png_actionPerformed()
650 throw new Error(MessageManager
651 .getString("error.png_generation_not_implemented"));
655 public void showHelp_actionPerformed()
659 String url = jmb.getHelpURL();
660 BrowserLauncher.openURL(url);
661 } catch (IOException ex)
664 .println("Show Chimera help failed with: " + ex.getMessage());
669 public AAStructureBindingModel getBinding()
675 * Ask Chimera to save its session to the designated file path, or to a
676 * temporary file if the path is null. Returns the file path if successful,
682 protected String saveSession(String filepath)
684 String pathUsed = filepath;
687 if (pathUsed == null)
689 String suffix = jmb.getSessionFileExtension();
690 File tempFile = File.createTempFile("chimera", suffix);
691 tempFile.deleteOnExit();
692 pathUsed = tempFile.getPath();
694 boolean result = jmb.saveSession(pathUsed);
697 this.chimeraSessionFile = pathUsed;
700 } catch (IOException e)
707 * Returns a string representing the state of the Chimera session. This is
708 * done by requesting Chimera to save its session to a temporary file, then
709 * reading the file contents. Returns an empty string on any error.
712 public String getStateInfo()
714 String sessionFile = saveSession(null);
715 if (sessionFile == null)
719 InputStream is = null;
722 File f = new File(sessionFile);
723 byte[] bytes = new byte[(int) f.length()];
724 is = new FileInputStream(sessionFile);
726 return new String(bytes);
727 } catch (IOException e)
737 } catch (IOException e)
746 protected void fitToWindow_actionPerformed()
752 public ViewerType getViewerType()
754 return ViewerType.CHIMERA;
758 protected String getViewerName()