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 = new JalviewChimeraBindingModel(this,
212 ap.getStructureSelectionManager(), pdbentrys, seqs, null);
213 addAlignmentPanel(ap);
214 useAlignmentPanelForColourbyseq(ap);
216 if (pdbentrys.length > 1)
218 useAlignmentPanelForSuperposition(ap);
220 jmb.setColourBySequence(true);
221 setSize(myWidth, myHeight);
224 addingStructures = false;
225 worker = new Thread(this);
228 this.addInternalFrameListener(new InternalFrameAdapter()
231 public void internalFrameClosing(
232 InternalFrameEvent internalFrameEvent)
241 * Create a new viewer from saved session state data including Chimera session
244 * @param chimeraSessionFile
248 * @param colourByChimera
249 * @param colourBySequence
252 public ChimeraViewFrame(String chimeraSessionFile,
253 AlignmentPanel alignPanel, PDBEntry[] pdbArray,
254 SequenceI[][] seqsArray, boolean colourByChimera,
255 boolean colourBySequence, String newViewId)
258 setViewId(newViewId);
259 this.chimeraSessionFile = chimeraSessionFile;
260 openNewChimera(alignPanel, pdbArray, seqsArray);
263 jmb.setColourBySequence(false);
264 seqColour.setSelected(false);
265 viewerColour.setSelected(true);
267 else if (colourBySequence)
269 jmb.setColourBySequence(true);
270 seqColour.setSelected(true);
271 viewerColour.setSelected(false);
276 * create a new viewer containing several structures, optionally superimposed
277 * using the given alignPanel.
283 public ChimeraViewFrame(PDBEntry[] pe, boolean alignAdded,
288 setAlignAddedStructures(alignAdded);
289 openNewChimera(ap, pe, seqs);
293 * Default constructor
295 public ChimeraViewFrame()
300 * closeViewer will decide whether or not to close this frame
301 * depending on whether user chooses to Cancel or not
303 setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
307 * Launch Chimera. If we have a chimera session file name, send Chimera the
308 * command to open its saved session file.
312 jmb.setFinishedInit(false);
313 Desktop.addInternalFrame(this,
314 jmb.getViewerTitle(getViewerName(), true), getBounds().width,
317 if (!jmb.launchChimera())
319 JvOptionPane.showMessageDialog(Desktop.desktop,
320 MessageManager.getString("label.chimera_failed"),
321 MessageManager.getString("label.error_loading_file"),
322 JvOptionPane.ERROR_MESSAGE);
327 if (this.chimeraSessionFile != null)
329 boolean opened = jmb.openSession(chimeraSessionFile);
332 System.err.println("An error occurred opening Chimera session file "
333 + chimeraSessionFile);
337 jmb.startChimeraListener();
341 * Close down this instance of Jalview's Chimera viewer, giving the user the
342 * option to close the associated Chimera window (process). They may wish to
343 * keep it open until they have had an opportunity to save any work.
345 * @param closeChimera
346 * if true, close any linked Chimera process; if false, prompt first
349 public void closeViewer(boolean closeChimera)
351 if (jmb != null && jmb.isChimeraRunning())
355 String prompt = MessageManager
356 .formatMessage("label.confirm_close_chimera", new Object[]
357 { jmb.getViewerTitle(getViewerName(), false) });
358 prompt = JvSwingUtils.wrapTooltip(true, prompt);
359 int confirm = JvOptionPane.showConfirmDialog(this, prompt,
360 MessageManager.getString("label.close_viewer"),
361 JvOptionPane.YES_NO_CANCEL_OPTION);
363 * abort closure if user hits escape or Cancel
365 if (confirm == JvOptionPane.CANCEL_OPTION
366 || confirm == JvOptionPane.CLOSED_OPTION)
370 closeChimera = confirm == JvOptionPane.YES_OPTION;
372 jmb.closeViewer(closeChimera);
374 setAlignmentPanel(null);
378 // TODO: check for memory leaks where instance isn't finalised because jmb
379 // holds a reference to the window
385 * Open any newly added PDB structures in Chimera, having first fetched data
386 * from PDB (if not already saved).
392 // todo - record which pdbids were successfully imported.
393 StringBuilder errormsgs = new StringBuilder(128);
394 StringBuilder files = new StringBuilder(128);
395 List<PDBEntry> filePDB = new ArrayList<>();
396 List<Integer> filePDBpos = new ArrayList<>();
397 PDBEntry thePdbEntry = null;
398 StructureFile pdb = null;
401 String[] curfiles = jmb.getStructureFiles(); // files currently in viewer
402 // TODO: replace with reference fetching/transfer code (validate PDBentry
404 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
407 thePdbEntry = jmb.getPdbEntry(pi);
408 if (thePdbEntry.getFile() == null)
411 * Retrieve PDB data, save to file, attach to PDBEntry
413 file = fetchPdbFile(thePdbEntry);
416 errormsgs.append("'" + thePdbEntry.getId() + "' ");
422 * Got file already - ignore if already loaded in Chimera.
424 file = new File(thePdbEntry.getFile()).getAbsoluteFile()
426 if (curfiles != null && curfiles.length > 0)
428 addingStructures = true; // already files loaded.
429 for (int c = 0; c < curfiles.length; c++)
431 if (curfiles[c].equals(file))
441 filePDB.add(thePdbEntry);
442 filePDBpos.add(Integer.valueOf(pi));
443 files.append(" \"" + Platform.escapeBackslashes(file) + "\"");
446 } catch (OutOfMemoryError oomerror)
448 new OOMWarning("Retrieving PDB files: " + thePdbEntry.getId(),
450 } catch (Exception ex)
452 ex.printStackTrace();
454 "When retrieving pdbfiles for '" + thePdbEntry.getId() + "'");
456 if (errormsgs.length() > 0)
459 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
460 MessageManager.formatMessage(
461 "label.pdb_entries_couldnt_be_retrieved", new Object[]
462 { errormsgs.toString() }),
463 MessageManager.getString("label.couldnt_load_file"),
464 JvOptionPane.ERROR_MESSAGE);
467 if (files.length() > 0)
469 jmb.setFinishedInit(false);
470 if (!addingStructures)
475 } catch (Exception ex)
477 Cache.log.error("Couldn't open Chimera viewer!", ex);
481 for (PDBEntry pe : filePDB)
484 if (pe.getFile() != null)
488 int pos = filePDBpos.get(num).intValue();
489 long startTime = startProgressBar(getViewerName() + " "
490 + MessageManager.getString("status.opening_file_for")
493 jmb.addSequence(pos, jmb.getSequence()[pos]);
494 File fl = new File(pe.getFile());
495 DataSourceType protocol = DataSourceType.URL;
500 protocol = DataSourceType.FILE;
502 } catch (Throwable e)
506 stopProgressBar("", startTime);
508 // Explicitly map to the filename used by Chimera ;
510 pdb = jmb.getSsm().setMapping(jmb.getSequence()[pos],
511 jmb.getChains()[pos], pe.getFile(), protocol,
512 getProgressIndicator());
513 stashFoundChains(pdb, pe.getFile());
515 } catch (OutOfMemoryError oomerror)
518 "When trying to open and map structures from Chimera!",
520 } catch (Exception ex)
523 "Couldn't open " + pe.getFile() + " in Chimera viewer!",
527 Cache.log.debug("File locations are " + files);
533 jmb.setFinishedInit(true);
534 jmb.setLoadingFromArchive(false);
537 * ensure that any newly discovered features (e.g. RESNUM)
538 * are added to any open feature settings dialog
540 FeatureRenderer fr = getBinding().getFeatureRenderer(null);
546 // refresh the sequence colours for the new structure(s)
547 for (AlignmentViewPanel ap : _colourwith)
549 jmb.updateColours(ap);
551 // do superposition if asked to
552 if (alignAddedStructures)
554 new Thread(new Runnable()
559 alignStructs_withAllAlignPanels();
563 addingStructures = false;
570 * Fetch PDB data and save to a local file. Returns the full path to the file,
571 * or null if fetch fails. TODO: refactor to common with Jmol ? duplication
573 * @param processingEntry
578 private void stashFoundChains(StructureFile pdb, String file)
580 for (int i = 0; i < pdb.getChains().size(); i++)
582 String chid = new String(
583 pdb.getId() + ":" + pdb.getChains().elementAt(i).id);
584 jmb.getChainNames().add(chid);
585 jmb.addChainFile(chid, file);
589 private String fetchPdbFile(PDBEntry processingEntry) throws Exception
591 String filePath = null;
592 Pdb pdbclient = new Pdb();
593 AlignmentI pdbseq = null;
594 String pdbid = processingEntry.getId();
595 long handle = System.currentTimeMillis()
596 + Thread.currentThread().hashCode();
599 * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
601 String msg = MessageManager.formatMessage("status.fetching_pdb",
604 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
605 // long hdl = startProgressBar(MessageManager.formatMessage(
606 // "status.fetching_pdb", new Object[]
610 pdbseq = pdbclient.getSequenceRecords(pdbid);
611 } catch (OutOfMemoryError oomerror)
613 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
616 msg = pdbid + " " + MessageManager.getString("label.state_completed");
617 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
618 // stopProgressBar(msg, hdl);
621 * If PDB data were saved and are not invalid (empty alignment), return the
624 if (pdbseq != null && pdbseq.getHeight() > 0)
626 // just use the file name from the first sequence's first PDBEntry
627 filePath = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
628 .elementAt(0).getFile()).getAbsolutePath();
629 processingEntry.setFile(filePath);
635 public void eps_actionPerformed(ActionEvent e)
637 throw new Error(MessageManager
638 .getString("error.eps_generation_not_implemented"));
642 public void png_actionPerformed(ActionEvent e)
644 throw new Error(MessageManager
645 .getString("error.png_generation_not_implemented"));
649 public void showHelp_actionPerformed(ActionEvent actionEvent)
653 String url = jmb.isChimeraX()
654 ? "http://www.rbvi.ucsf.edu/chimerax/docs/user/index.html"
655 : "https://www.cgl.ucsf.edu/chimera/docs/UsersGuide";
656 BrowserLauncher.openURL(url);
657 } catch (IOException ex)
660 .println("Show Chimera help failed with: " + ex.getMessage());
665 public AAStructureBindingModel getBinding()
671 * Ask Chimera to save its session to the designated file path, or to a
672 * temporary file if the path is null. Returns the file path if successful,
678 protected String saveSession(String filepath)
680 String pathUsed = filepath;
683 if (pathUsed == null)
685 String suffix = jmb.isChimeraX() ? ".cxs" : ".py";
686 File tempFile = File.createTempFile("chimera", suffix);
687 tempFile.deleteOnExit();
688 pathUsed = tempFile.getPath();
690 boolean result = jmb.saveSession(pathUsed);
693 this.chimeraSessionFile = pathUsed;
696 } catch (IOException e)
703 * Returns a string representing the state of the Chimera session. This is
704 * done by requesting Chimera to save its session to a temporary file, then
705 * reading the file contents. Returns an empty string on any error.
708 public String getStateInfo()
710 String sessionFile = saveSession(null);
711 if (sessionFile == null)
715 InputStream is = null;
718 File f = new File(sessionFile);
719 byte[] bytes = new byte[(int) f.length()];
720 is = new FileInputStream(sessionFile);
722 return new String(bytes);
723 } catch (IOException e)
733 } catch (IOException e)
742 protected void fitToWindow_actionPerformed()
748 public ViewerType getViewerType()
750 return ViewerType.CHIMERA;
754 protected String getViewerName()
760 * Sends commands to align structures according to associated alignment(s).
765 protected String alignStructs_withAllAlignPanels()
767 String reply = super.alignStructs_withAllAlignPanels();
770 statusBar.setText("Superposition failed: " + reply);