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.Graphics2D;
29 import java.awt.RenderingHints;
31 import java.lang.reflect.InvocationTargetException;
32 import java.util.List;
33 import java.util.Locale;
36 import javax.swing.JPanel;
37 import javax.swing.JSplitPane;
38 import javax.swing.SwingUtilities;
39 import javax.swing.event.InternalFrameAdapter;
40 import javax.swing.event.InternalFrameEvent;
42 import jalview.api.AlignmentViewPanel;
43 import jalview.bin.Console;
44 import jalview.datamodel.PDBEntry;
45 import jalview.datamodel.SequenceI;
46 import jalview.datamodel.StructureViewerModel;
47 import jalview.datamodel.StructureViewerModel.StructureData;
48 import jalview.gui.ImageExporter.ImageWriterI;
49 import jalview.gui.StructureViewer.ViewerType;
50 import jalview.io.exceptions.ImageOutputException;
51 import jalview.structure.StructureCommand;
52 import jalview.structures.models.AAStructureBindingModel;
53 import jalview.util.BrowserLauncher;
54 import jalview.util.ImageMaker;
55 import jalview.util.ImageMaker.TYPE;
56 import jalview.util.MessageManager;
57 import jalview.util.Platform;
58 import jalview.util.imagemaker.BitmapImageSizing;
60 public class AppJmol extends StructureViewerBase
62 // ms to wait for Jmol to load files
63 private static final int JMOL_LOAD_TIMEOUT = 20000;
65 private static final String SPACE = " ";
67 private static final String QUOTE = "\"";
75 RenderPanel renderPanel;
84 * - add the alignment panel to the list used for colouring these
87 * - add the alignment panel to the list used for aligning these
89 * @param leaveColouringToJmol
90 * - do not update the colours from any other source. Jmol is
96 public AppJmol(StructureViewerModel viewerModel, AlignmentPanel ap,
97 String sessionFile, String viewid)
99 Map<File, StructureData> pdbData = viewerModel.getFileData();
100 PDBEntry[] pdbentrys = new PDBEntry[pdbData.size()];
101 SequenceI[][] seqs = new SequenceI[pdbData.size()][];
103 for (StructureData data : pdbData.values())
105 PDBEntry pdbentry = new PDBEntry(data.getPdbId(), null,
106 PDBEntry.Type.PDB, data.getFilePath());
107 pdbentrys[i] = pdbentry;
108 List<SequenceI> sequencesForPdb = data.getSeqList();
109 seqs[i] = sequencesForPdb
110 .toArray(new SequenceI[sequencesForPdb.size()]);
114 // TODO: check if protocol is needed to be set, and if chains are
116 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
117 pdbentrys, seqs, null);
119 jmb.setLoadingFromArchive(true);
120 addAlignmentPanel(ap);
121 if (viewerModel.isAlignWithPanel())
123 useAlignmentPanelForSuperposition(ap);
126 boolean useToColour = viewerModel.isColourWithAlignPanel();
127 boolean leaveColouringToJmol = viewerModel.isColourByViewer();
128 if (leaveColouringToJmol || !useToColour)
130 jmb.setColourBySequence(false);
131 seqColour.setSelected(false);
132 viewerColour.setSelected(true);
134 else if (useToColour)
136 useAlignmentPanelForColourbyseq(ap);
137 jmb.setColourBySequence(true);
138 seqColour.setSelected(true);
139 viewerColour.setSelected(false);
142 this.setBounds(viewerModel.getX(), viewerModel.getY(),
143 viewerModel.getWidth(), viewerModel.getHeight());
146 this.addInternalFrameListener(new InternalFrameAdapter()
149 public void internalFrameClosing(
150 InternalFrameEvent internalFrameEvent)
155 StringBuilder cmd = new StringBuilder();
156 cmd.append("load FILES ").append(QUOTE)
157 .append(Platform.escapeBackslashes(sessionFile)).append(QUOTE);
158 initJmol(cmd.toString());
162 protected void initMenus()
167 .setText(MessageManager.getString("label.colour_with_jmol"));
168 viewerColour.setToolTipText(MessageManager
169 .getString("label.let_jmol_manage_structure_colours"));
173 * display a single PDB structure in a new Jmol view
180 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
181 final AlignmentPanel ap)
183 setProgressIndicator(ap.alignFrame);
185 openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
190 private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
191 PDBEntry[] pdbentrys, SequenceI[][] seqs)
193 setProgressIndicator(ap.alignFrame);
194 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
195 pdbentrys, seqs, null);
196 addAlignmentPanel(ap);
197 useAlignmentPanelForColourbyseq(ap);
199 alignAddedStructures = alignAdded;
200 if (pdbentrys.length > 1)
202 useAlignmentPanelForSuperposition(ap);
205 jmb.setColourBySequence(true);
206 setSize(400, 400); // probably should be a configurable/dynamic default here
208 addingStructures = false;
209 worker = new Thread(this);
212 this.addInternalFrameListener(new InternalFrameAdapter()
215 public void internalFrameClosing(
216 InternalFrameEvent internalFrameEvent)
225 * create a new Jmol containing several structures optionally superimposed
226 * using the given alignPanel.
230 * - true to superimpose
234 public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
237 openNewJmol(ap, alignAdded, pe, seqs);
240 void initJmol(String command)
242 jmb.setFinishedInit(false);
243 renderPanel = new RenderPanel();
244 // TODO: consider waiting until the structure/view is fully loaded before
246 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
247 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
248 getBounds().width, getBounds().height);
249 if (scriptWindow == null)
251 BorderLayout bl = new BorderLayout();
254 scriptWindow = new JPanel(bl);
255 scriptWindow.setVisible(false);
258 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
260 // jmb.newJmolPopup("Jmol");
265 jmb.executeCommand(new StructureCommand(command), false);
266 jmb.executeCommand(new StructureCommand("set hoverDelay=0.1"), false);
267 jmb.setFinishedInit(true);
276 List<String> files = jmb.fetchPdbFiles(this);
277 if (files.size() > 0)
279 showFilesInViewer(files);
289 * Either adds the given files to a structure viewer or opens a new viewer to
293 * list of absolute paths to structure files
295 void showFilesInViewer(List<String> files)
297 long lastnotify = jmb.getLoadNotifiesHandled();
298 StringBuilder fileList = new StringBuilder();
299 for (String s : files)
301 fileList.append(SPACE).append(QUOTE)
302 .append(Platform.escapeBackslashes(s)).append(QUOTE);
304 String filesString = fileList.toString();
306 if (!addingStructures)
310 initJmol("load FILES " + filesString);
311 } catch (OutOfMemoryError oomerror)
313 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
314 Console.debug("File locations are " + filesString);
315 } catch (Exception ex)
317 Console.error("Couldn't open Jmol viewer!", ex);
318 ex.printStackTrace();
324 StringBuilder cmd = new StringBuilder();
325 cmd.append("loadingJalviewdata=true\nload APPEND ");
326 cmd.append(filesString);
327 cmd.append("\nloadingJalviewdata=null");
328 final StructureCommand command = new StructureCommand(cmd.toString());
329 lastnotify = jmb.getLoadNotifiesHandled();
333 jmb.executeCommand(command, false);
334 } catch (OutOfMemoryError oomerror)
336 new OOMWarning("When trying to add structures to the Jmol viewer!",
338 Console.debug("File locations are " + filesString);
340 } catch (Exception ex)
342 Console.error("Couldn't add files to Jmol viewer!", ex);
343 ex.printStackTrace();
348 // need to wait around until script has finished
349 int waitMax = JMOL_LOAD_TIMEOUT;
352 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
353 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
354 && jmb.getStructureFiles().length == files.size()))
358 Console.debug("Waiting around for jmb notify.");
359 waitTotal += waitFor;
361 // Thread.sleep() throws an exception in JS
362 Thread.sleep(waitFor);
363 } catch (Exception e)
366 if (waitTotal > waitMax)
368 System.err.println("Timed out waiting for Jmol to load files after "
370 // System.err.println("finished: " + jmb.isFinishedInit()
371 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
372 // + "; files: " + files.toString());
373 jmb.getStructureFiles();
378 // refresh the sequence colours for the new structure(s)
379 for (AlignmentViewPanel ap : _colourwith)
381 jmb.updateColours(ap);
383 // do superposition if asked to
384 if (alignAddedStructures)
386 alignAddedStructures();
388 addingStructures = false;
392 * Queues a thread to align structures with Jalview alignments
394 void alignAddedStructures()
396 javax.swing.SwingUtilities.invokeLater(new Runnable()
401 if (jmb.jmolViewer.isScriptExecuting())
403 SwingUtilities.invokeLater(this);
407 } catch (InterruptedException q)
414 alignStructsWithAllAlignPanels();
422 * Outputs the Jmol viewer image as an image file, after prompting the user to
423 * choose a file and (for EPS) choice of Text or Lineart character rendering
424 * (unless a preference for this is set)
429 public void makePDBImage(ImageMaker.TYPE type)
432 makePDBImage(null, type, null,
433 BitmapImageSizing.nullBitmapImageSizing());
434 } catch (ImageOutputException ioex) {
435 Console.error("Unexpected error whilst writing "+type.toString(),ioex);
439 public void makePDBImage(File file, ImageMaker.TYPE type, String renderer,
440 BitmapImageSizing userBis) throws ImageOutputException
442 int width = getWidth();
443 int height = getHeight();
445 BitmapImageSizing bis = ImageMaker.getScaleWidthHeight(width, height,
447 float usescale = bis.scale;
448 int usewidth = bis.width;
449 int useheight = bis.height;
451 ImageWriterI writer = new ImageWriterI()
454 public void exportImage(Graphics g) throws Exception
456 Graphics2D ig2 = (Graphics2D) g;
457 ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
458 RenderingHints.VALUE_ANTIALIAS_ON);
459 if (type == TYPE.PNG && usescale > 0.0f)
461 // for a scaled image, this scales down a bigger image to give the
465 ig2.scale(1 / usescale, 1 / usescale);
469 jmb.jmolViewer.antialiased = true;
470 jmb.jmolViewer.requestRepaintAndWait("image export");
471 jmb.jmolViewer.renderScreenImage(ig2, usewidth, useheight);
474 String view = MessageManager.getString("action.view")
475 .toLowerCase(Locale.ROOT);
476 final ImageExporter exporter = new ImageExporter(writer,
477 getProgressIndicator(), type, getTitle());
478 // hack to pass back and throw to caller
479 final Throwable[] exceptions = new Throwable[1];
480 exceptions[0] = null;
481 final AppJmol us = this;
484 SwingUtilities.invokeAndWait(new Runnable()
491 exporter.doExport(file, us, width, height, view, renderer,
493 } catch (Throwable t)
499 } catch (InvocationTargetException e)
501 throw new ImageOutputException(
502 "Unexpected error when generating image", e);
503 } catch (InterruptedException e)
505 Console.debug("Interrupted whilst waiting for image export", e);
507 if (exceptions[0] != null)
509 if (exceptions[0] instanceof ImageOutputException)
511 throw ((ImageOutputException) exceptions[0]);
515 throw new ImageOutputException(
516 "Unexpected error when generating image", exceptions[0]);
522 public void showHelp_actionPerformed()
526 BrowserLauncher // BH 2018
527 .openURL("http://wiki.jmol.org");// http://jmol.sourceforge.net/docs/JmolUserGuide/");
528 } catch (Exception ex)
530 System.err.println("Show Jmol help failed with: " + ex.getMessage());
535 public void showConsole(boolean showConsole)
539 if (splitPane == null)
541 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
542 splitPane.setTopComponent(renderPanel);
543 splitPane.setBottomComponent(scriptWindow);
544 this.getContentPane().add(splitPane, BorderLayout.CENTER);
545 splitPane.setDividerLocation(getHeight() - 200);
546 scriptWindow.setVisible(true);
547 scriptWindow.validate();
548 splitPane.validate();
554 if (splitPane != null)
556 splitPane.setVisible(false);
561 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
567 class RenderPanel extends JPanel
569 final Dimension currentSize = new Dimension();
572 public void paintComponent(Graphics g)
574 getSize(currentSize);
576 if (jmb != null && jmb.hasFileLoadingError())
578 g.setColor(Color.black);
579 g.fillRect(0, 0, currentSize.width, currentSize.height);
580 g.setColor(Color.white);
581 g.setFont(new Font("Verdana", Font.BOLD, 14));
582 g.drawString(MessageManager.getString("label.error_loading_file")
583 + "...", 20, currentSize.height / 2);
584 StringBuffer sb = new StringBuffer();
586 for (int e = 0; e < jmb.getPdbCount(); e++)
588 sb.append(jmb.getPdbEntry(e).getId());
589 if (e < jmb.getPdbCount() - 1)
594 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
597 g.drawString(sb.toString(), 20, currentSize.height / 2
598 - lines * g.getFontMetrics().getHeight());
602 else if (jmb == null || jmb.jmolViewer == null
603 || !jmb.isFinishedInit())
605 g.setColor(Color.black);
606 g.fillRect(0, 0, currentSize.width, currentSize.height);
607 g.setColor(Color.white);
608 g.setFont(new Font("Verdana", Font.BOLD, 14));
609 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
610 20, currentSize.height / 2);
614 jmb.jmolViewer.renderScreenImage(g, currentSize.width,
621 public AAStructureBindingModel getBinding()
627 public ViewerType getViewerType()
629 return ViewerType.JMOL;
633 protected String getViewerName()