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 java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Dimension;
27 import java.awt.Graphics;
28 import java.awt.Rectangle;
30 import java.util.ArrayList;
31 import java.util.List;
33 import javax.swing.JPanel;
34 import javax.swing.JSplitPane;
35 import javax.swing.SwingUtilities;
36 import javax.swing.event.InternalFrameAdapter;
37 import javax.swing.event.InternalFrameEvent;
39 import jalview.api.AlignmentViewPanel;
40 import jalview.bin.Cache;
41 import jalview.datamodel.AlignmentI;
42 import jalview.datamodel.PDBEntry;
43 import jalview.datamodel.SequenceI;
44 import jalview.gui.StructureViewer.ViewerType;
45 import jalview.structure.StructureCommand;
46 import jalview.structures.models.AAStructureBindingModel;
47 import jalview.util.BrowserLauncher;
48 import jalview.util.ImageMaker;
49 import jalview.util.MessageManager;
50 import jalview.util.Platform;
51 import jalview.ws.dbsources.Pdb;
53 public class AppJmol extends StructureViewerBase
55 // ms to wait for Jmol to load files
56 private static final int JMOL_LOAD_TIMEOUT = 20000;
58 private static final String SPACE = " ";
60 private static final String QUOTE = "\"";
68 RenderPanel renderPanel;
77 * - add the alignment panel to the list used for colouring these
80 * - add the alignment panel to the list used for aligning these
82 * @param leaveColouringToJmol
83 * - do not update the colours from any other source. Jmol is
89 public AppJmol(String[] files, String[] ids, SequenceI[][] seqs,
90 AlignmentPanel ap, boolean usetoColour, boolean useToAlign,
91 boolean leaveColouringToJmol, String loadStatus, Rectangle bounds,
94 PDBEntry[] pdbentrys = new PDBEntry[files.length];
95 for (int i = 0; i < pdbentrys.length; i++)
97 // PDBEntry pdbentry = new PDBEntry(files[i], ids[i]);
98 PDBEntry pdbentry = new PDBEntry(ids[i], null, PDBEntry.Type.PDB,
100 pdbentrys[i] = pdbentry;
102 // / TODO: check if protocol is needed to be set, and if chains are
104 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
105 pdbentrys, seqs, null);
107 jmb.setLoadingFromArchive(true);
108 addAlignmentPanel(ap);
111 useAlignmentPanelForSuperposition(ap);
114 if (leaveColouringToJmol || !usetoColour)
116 jmb.setColourBySequence(false);
117 seqColour.setSelected(false);
118 viewerColour.setSelected(true);
120 else if (usetoColour)
122 useAlignmentPanelForColourbyseq(ap);
123 jmb.setColourBySequence(true);
124 seqColour.setSelected(true);
125 viewerColour.setSelected(false);
127 this.setBounds(bounds);
129 // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
130 // bounds.width,bounds.height);
132 this.addInternalFrameListener(new InternalFrameAdapter()
135 public void internalFrameClosing(
136 InternalFrameEvent internalFrameEvent)
141 initJmol(loadStatus); // pdbentry, seq, JBPCHECK!
145 protected void initMenus()
149 viewerActionMenu.setText(MessageManager.getString("label.jmol"));
152 .setText(MessageManager.getString("label.colour_with_jmol"));
153 viewerColour.setToolTipText(MessageManager
154 .getString("label.let_jmol_manage_structure_colours"));
158 * display a single PDB structure in a new Jmol view
165 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
166 final AlignmentPanel ap)
168 setProgressIndicator(ap.alignFrame);
170 openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
175 private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
176 PDBEntry[] pdbentrys,
179 setProgressIndicator(ap.alignFrame);
180 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
181 pdbentrys, seqs, null);
182 addAlignmentPanel(ap);
183 useAlignmentPanelForColourbyseq(ap);
185 alignAddedStructures = alignAdded;
186 if (pdbentrys.length > 1)
188 useAlignmentPanelForSuperposition(ap);
191 jmb.setColourBySequence(true);
192 setSize(400, 400); // probably should be a configurable/dynamic default here
194 addingStructures = false;
195 worker = new Thread(this);
198 this.addInternalFrameListener(new InternalFrameAdapter()
201 public void internalFrameClosing(
202 InternalFrameEvent internalFrameEvent)
211 * create a new Jmol containing several structures optionally superimposed
212 * using the given alignPanel.
216 * - true to superimpose
220 public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
223 openNewJmol(ap, alignAdded, pe, seqs);
227 void initJmol(String command)
229 jmb.setFinishedInit(false);
230 renderPanel = new RenderPanel();
231 // TODO: consider waiting until the structure/view is fully loaded before
233 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
234 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
235 getBounds().width, getBounds().height);
236 if (scriptWindow == null)
238 BorderLayout bl = new BorderLayout();
241 scriptWindow = new JPanel(bl);
242 scriptWindow.setVisible(false);
245 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
247 // jmb.newJmolPopup("Jmol");
252 jmb.executeCommand(new StructureCommand(command), false);
253 jmb.executeCommand(new StructureCommand("set hoverDelay=0.1"), false);
254 jmb.setFinishedInit(true);
258 public void closeViewer(boolean closeExternalViewer)
260 // Jmol does not use an external viewer
265 setAlignmentPanel(null);
269 // TODO: check for memory leaks where instance isn't finalised because jmb
270 // holds a reference to the window
280 List<String> files = fetchPdbFiles();
281 if (files.size() > 0)
283 showFilesInViewer(files);
293 * Either adds the given files to a structure viewer or opens a new viewer to
297 * list of absolute paths to structure files
299 void showFilesInViewer(List<String> files)
301 long lastnotify = jmb.getLoadNotifiesHandled();
302 StringBuilder fileList = new StringBuilder();
303 for (String s : files)
305 fileList.append(SPACE).append(QUOTE)
306 .append(Platform.escapeBackslashes(s)).append(QUOTE);
308 String filesString = fileList.toString();
310 if (!addingStructures)
314 initJmol("load FILES " + filesString);
315 } catch (OutOfMemoryError oomerror)
317 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
318 Cache.log.debug("File locations are " + filesString);
319 } catch (Exception ex)
321 Cache.log.error("Couldn't open Jmol viewer!", ex);
326 StringBuilder cmd = new StringBuilder();
327 cmd.append("loadingJalviewdata=true\nload APPEND ");
328 cmd.append(filesString);
329 cmd.append("\nloadingJalviewdata=null");
330 final StructureCommand command = new StructureCommand(cmd.toString());
331 lastnotify = jmb.getLoadNotifiesHandled();
335 jmb.executeCommand(command, false);
336 } catch (OutOfMemoryError oomerror)
338 new OOMWarning("When trying to add structures to the Jmol viewer!",
340 Cache.log.debug("File locations are " + filesString);
341 } catch (Exception ex)
343 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
347 // need to wait around until script has finished
348 int waitMax = JMOL_LOAD_TIMEOUT;
351 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
352 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
353 && jmb.getStructureFiles().length == files.size()))
357 Cache.log.debug("Waiting around for jmb notify.");
358 Thread.sleep(waitFor);
359 waitTotal += waitFor;
360 } catch (Exception e)
363 if (waitTotal > waitMax)
365 System.err.println("Timed out waiting for Jmol to load files after "
367 // System.err.println("finished: " + jmb.isFinishedInit()
368 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
369 // + "; files: " + files.toString());
370 jmb.getStructureFiles();
375 // refresh the sequence colours for the new structure(s)
376 for (AlignmentViewPanel ap : _colourwith)
378 jmb.updateColours(ap);
380 // do superposition if asked to
381 if (alignAddedStructures)
383 alignAddedStructures();
385 addingStructures = false;
389 * Queues a thread to align structures with Jalview alignments
391 void alignAddedStructures()
393 javax.swing.SwingUtilities.invokeLater(new Runnable()
398 if (jmb.jmolViewer.isScriptExecuting())
400 SwingUtilities.invokeLater(this);
404 } catch (InterruptedException q)
411 alignStructsWithAllAlignPanels();
419 * Retrieves and saves as file any modelled PDB entries for which we do not
420 * already have a file saved. Returns a list of absolute paths to structure
421 * files which were either retrieved, or already stored but not modelled in
422 * the structure viewer (i.e. files to add to the viewer display).
426 List<String> fetchPdbFiles()
428 // todo - record which pdbids were successfully imported.
429 StringBuilder errormsgs = new StringBuilder();
431 List<String> files = new ArrayList<>();
435 String[] filesInViewer = jmb.getStructureFiles();
436 // TODO: replace with reference fetching/transfer code (validate PDBentry
438 Pdb pdbclient = new Pdb();
439 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
441 String file = jmb.getPdbEntry(pi).getFile();
444 // todo: extract block as method and pull up (also ChimeraViewFrame)
445 // retrieve the pdb and store it locally
446 AlignmentI pdbseq = null;
447 pdbid = jmb.getPdbEntry(pi).getId();
448 long hdl = pdbid.hashCode() - System.currentTimeMillis();
449 setProgressMessage(MessageManager
450 .formatMessage("status.fetching_pdb", new String[]
454 pdbseq = pdbclient.getSequenceRecords(pdbid);
455 } catch (OutOfMemoryError oomerror)
457 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
458 } catch (Exception ex)
460 ex.printStackTrace();
461 errormsgs.append("'").append(pdbid).append("'");
465 MessageManager.getString("label.state_completed"), hdl);
469 // just transfer the file name from the first sequence's first
471 file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
472 .elementAt(0).getFile()).getAbsolutePath();
473 jmb.getPdbEntry(pi).setFile(file);
478 errormsgs.append("'").append(pdbid).append("' ");
483 if (filesInViewer != null && filesInViewer.length > 0)
485 addingStructures = true; // already files loaded.
486 for (int c = 0; c < filesInViewer.length; c++)
488 if (Platform.pathEquals(filesInViewer[c], file))
501 } catch (OutOfMemoryError oomerror)
503 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
504 } catch (Exception ex)
506 ex.printStackTrace();
507 errormsgs.append("When retrieving pdbfiles : current was: '")
508 .append(pdbid).append("'");
510 if (errormsgs.length() > 0)
512 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
513 MessageManager.formatMessage(
514 "label.pdb_entries_couldnt_be_retrieved", new String[]
515 { errormsgs.toString() }),
516 MessageManager.getString("label.couldnt_load_file"),
517 JvOptionPane.ERROR_MESSAGE);
523 public void eps_actionPerformed()
525 makePDBImage(ImageMaker.TYPE.EPS);
529 public void png_actionPerformed()
531 makePDBImage(ImageMaker.TYPE.PNG);
534 void makePDBImage(ImageMaker.TYPE type)
536 int width = getWidth();
537 int height = getHeight();
541 if (type == ImageMaker.TYPE.PNG)
543 im = new ImageMaker(this, ImageMaker.TYPE.PNG,
544 "Make PNG image from view",
545 width, height, null, null, null, 0, false);
547 else if (type == ImageMaker.TYPE.EPS)
549 im = new ImageMaker(this, ImageMaker.TYPE.EPS,
550 "Make EPS file from view",
551 width, height, null, this.getTitle(), null, 0, false);
555 im = new jalview.util.ImageMaker(this,
556 ImageMaker.TYPE.SVG, "Make SVG file from PCA",
557 width, height, null, this.getTitle(), null, 0, false);
560 if (im.getGraphics() != null)
562 jmb.jmolViewer.renderScreenImage(im.getGraphics(), width, height);
568 public void showHelp_actionPerformed()
573 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
574 } catch (Exception ex)
576 System.err.println("Show Jmol help failed with: " + ex.getMessage());
581 public void showConsole(boolean showConsole)
585 if (splitPane == null)
587 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
588 splitPane.setTopComponent(renderPanel);
589 splitPane.setBottomComponent(scriptWindow);
590 this.getContentPane().add(splitPane, BorderLayout.CENTER);
591 splitPane.setDividerLocation(getHeight() - 200);
592 scriptWindow.setVisible(true);
593 scriptWindow.validate();
594 splitPane.validate();
600 if (splitPane != null)
602 splitPane.setVisible(false);
607 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
613 class RenderPanel extends JPanel
615 final Dimension currentSize = new Dimension();
618 public void paintComponent(Graphics g)
620 getSize(currentSize);
622 if (jmb != null && jmb.hasFileLoadingError())
624 g.setColor(Color.black);
625 g.fillRect(0, 0, currentSize.width, currentSize.height);
626 g.setColor(Color.white);
627 g.setFont(new Font("Verdana", Font.BOLD, 14));
628 g.drawString(MessageManager.getString("label.error_loading_file")
629 + "...", 20, currentSize.height / 2);
630 StringBuffer sb = new StringBuffer();
632 for (int e = 0; e < jmb.getPdbCount(); e++)
634 sb.append(jmb.getPdbEntry(e).getId());
635 if (e < jmb.getPdbCount() - 1)
640 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
643 g.drawString(sb.toString(), 20, currentSize.height / 2
644 - lines * g.getFontMetrics().getHeight());
648 else if (jmb == null || jmb.jmolViewer == null || !jmb.isFinishedInit())
650 g.setColor(Color.black);
651 g.fillRect(0, 0, currentSize.width, currentSize.height);
652 g.setColor(Color.white);
653 g.setFont(new Font("Verdana", Font.BOLD, 14));
654 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
655 20, currentSize.height / 2);
659 jmb.jmolViewer.renderScreenImage(g, currentSize.width,
666 public AAStructureBindingModel getBinding()
672 public ViewerType getViewerType()
674 return ViewerType.JMOL;
678 protected String getViewerName()