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.util.List;
32 import java.util.Locale;
34 import java.util.concurrent.Executors;
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.bin.Jalview;
45 import jalview.datamodel.PDBEntry;
46 import jalview.datamodel.SequenceI;
47 import jalview.datamodel.StructureViewerModel;
48 import jalview.datamodel.StructureViewerModel.StructureData;
49 import jalview.gui.ImageExporter.ImageWriterI;
50 import jalview.gui.StructureViewer.ViewerType;
51 import jalview.io.exceptions.ImageOutputException;
52 import jalview.structure.StructureCommand;
53 import jalview.structures.models.AAStructureBindingModel;
54 import jalview.util.BrowserLauncher;
55 import jalview.util.ImageMaker;
56 import jalview.util.ImageMaker.TYPE;
57 import jalview.util.MessageManager;
58 import jalview.util.Platform;
59 import jalview.util.imagemaker.BitmapImageSizing;
61 public class AppJmol extends StructureViewerBase
63 // ms to wait for Jmol to load files
64 private static final int JMOL_LOAD_TIMEOUT = 20000;
66 private static final String SPACE = " ";
68 private static final String QUOTE = "\"";
76 RenderPanel renderPanel;
85 * - add the alignment panel to the list used for colouring these
88 * - add the alignment panel to the list used for aligning these
90 * @param leaveColouringToJmol
91 * - do not update the colours from any other source. Jmol is
97 public AppJmol(StructureViewerModel viewerModel, AlignmentPanel ap,
98 String sessionFile, String viewid)
100 Map<File, StructureData> pdbData = viewerModel.getFileData();
101 PDBEntry[] pdbentrys = new PDBEntry[pdbData.size()];
102 SequenceI[][] seqs = new SequenceI[pdbData.size()][];
104 for (StructureData data : pdbData.values())
106 PDBEntry pdbentry = new PDBEntry(data.getPdbId(), null,
107 PDBEntry.Type.PDB, data.getFilePath());
108 pdbentrys[i] = pdbentry;
109 List<SequenceI> sequencesForPdb = data.getSeqList();
110 seqs[i] = sequencesForPdb
111 .toArray(new SequenceI[sequencesForPdb.size()]);
115 // TODO: check if protocol is needed to be set, and if chains are
117 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
118 pdbentrys, seqs, null);
120 jmb.setLoadingFromArchive(true);
121 addAlignmentPanel(ap);
122 if (viewerModel.isAlignWithPanel())
124 useAlignmentPanelForSuperposition(ap);
127 boolean useToColour = viewerModel.isColourWithAlignPanel();
128 boolean leaveColouringToJmol = viewerModel.isColourByViewer();
129 if (leaveColouringToJmol || !useToColour)
131 jmb.setColourBySequence(false);
132 seqColour.setSelected(false);
133 viewerColour.setSelected(true);
135 else if (useToColour)
137 useAlignmentPanelForColourbyseq(ap);
138 jmb.setColourBySequence(true);
139 seqColour.setSelected(true);
140 viewerColour.setSelected(false);
143 this.setBounds(viewerModel.getX(), viewerModel.getY(),
144 viewerModel.getWidth(), viewerModel.getHeight());
147 this.addInternalFrameListener(new InternalFrameAdapter()
150 public void internalFrameClosing(
151 InternalFrameEvent internalFrameEvent)
156 StringBuilder cmd = new StringBuilder();
157 cmd.append("load FILES ").append(QUOTE)
158 .append(Platform.escapeBackslashes(sessionFile)).append(QUOTE);
159 initJmol(cmd.toString());
163 protected void initMenus()
168 .setText(MessageManager.getString("label.colour_with_jmol"));
169 viewerColour.setToolTipText(MessageManager
170 .getString("label.let_jmol_manage_structure_colours"));
174 * display a single PDB structure in a new Jmol view
181 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
182 final AlignmentPanel ap)
184 setProgressIndicator(ap.alignFrame);
186 openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
191 private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
192 PDBEntry[] pdbentrys, SequenceI[][] seqs)
194 setProgressIndicator(ap.alignFrame);
195 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
196 pdbentrys, seqs, null);
197 addAlignmentPanel(ap);
198 useAlignmentPanelForColourbyseq(ap);
200 alignAddedStructures = alignAdded;
201 if (pdbentrys.length > 1)
203 useAlignmentPanelForSuperposition(ap);
206 jmb.setColourBySequence(true);
207 setSize(400, 400); // probably should be a configurable/dynamic default here
209 addingStructures = false;
210 worker = new Thread(this);
213 this.addInternalFrameListener(new InternalFrameAdapter()
216 public void internalFrameClosing(
217 InternalFrameEvent internalFrameEvent)
226 * create a new Jmol containing several structures optionally superimposed
227 * using the given alignPanel.
231 * - true to superimpose
235 public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
238 openNewJmol(ap, alignAdded, pe, seqs);
241 void initJmol(String command)
243 jmb.setFinishedInit(false);
244 renderPanel = new RenderPanel();
245 // TODO: consider waiting until the structure/view is fully loaded before
247 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
248 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
249 getBounds().width, getBounds().height);
250 if (scriptWindow == null)
252 BorderLayout bl = new BorderLayout();
255 scriptWindow = new JPanel(bl);
256 scriptWindow.setVisible(false);
259 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
261 // jmb.newJmolPopup("Jmol");
266 jmb.executeCommand(new StructureCommand(command), false);
267 jmb.executeCommand(new StructureCommand("set hoverDelay=0.1"), false);
268 jmb.executeCommand(new StructureCommand("set antialiasdisplay on"),
270 jmb.setFinishedInit(true);
279 List<String> files = jmb.fetchPdbFiles(this);
280 if (files.size() > 0)
282 showFilesInViewer(files);
292 * Either adds the given files to a structure viewer or opens a new viewer to
296 * list of absolute paths to structure files
298 void showFilesInViewer(List<String> files)
300 long lastnotify = jmb.getLoadNotifiesHandled();
301 StringBuilder fileList = new StringBuilder();
302 for (String s : files)
304 fileList.append(SPACE).append(QUOTE)
305 .append(Platform.escapeBackslashes(s)).append(QUOTE);
307 String filesString = fileList.toString();
309 if (!addingStructures)
313 initJmol("load FILES " + filesString);
314 } catch (OutOfMemoryError oomerror)
316 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
317 Console.debug("File locations are " + filesString);
318 } catch (Exception ex)
320 Console.error("Couldn't open Jmol viewer!", ex);
321 ex.printStackTrace();
327 StringBuilder cmd = new StringBuilder();
328 cmd.append("loadingJalviewdata=true\nload APPEND ");
329 cmd.append(filesString);
330 cmd.append("\nloadingJalviewdata=null");
331 final StructureCommand command = new StructureCommand(cmd.toString());
332 lastnotify = jmb.getLoadNotifiesHandled();
336 jmb.executeCommand(command, false);
337 } catch (OutOfMemoryError oomerror)
339 new OOMWarning("When trying to add structures to the Jmol viewer!",
341 Console.debug("File locations are " + filesString);
343 } catch (Exception ex)
345 Console.error("Couldn't add files to Jmol viewer!", ex);
346 ex.printStackTrace();
351 // need to wait around until script has finished
352 int waitMax = JMOL_LOAD_TIMEOUT;
355 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
356 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
357 && jmb.getStructureFiles().length == files.size()))
361 Console.debug("Waiting around for jmb notify.");
362 waitTotal += waitFor;
364 // Thread.sleep() throws an exception in JS
365 Thread.sleep(waitFor);
366 } catch (Exception e)
369 if (waitTotal > waitMax)
371 jalview.bin.Console.errPrintln(
372 "Timed out waiting for Jmol to load files after "
374 // jalview.bin.Console.errPrintln("finished: " + jmb.isFinishedInit()
375 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
376 // + "; files: " + files.toString());
377 jmb.getStructureFiles();
382 // refresh the sequence colours for the new structure(s)
383 for (AlignmentViewPanel ap : _colourwith)
385 jmb.updateColours(ap);
387 // do superposition if asked to
388 if (alignAddedStructures)
390 alignAddedStructures();
392 addingStructures = false;
396 * Queues a thread to align structures with Jalview alignments
398 void alignAddedStructures()
400 javax.swing.SwingUtilities.invokeLater(new Runnable()
405 if (jmb.jmolViewer.isScriptExecuting())
407 SwingUtilities.invokeLater(this);
411 } catch (InterruptedException q)
418 alignStructsWithAllAlignPanels();
426 * Outputs the Jmol viewer image as an image file, after prompting the user to
427 * choose a file and (for EPS) choice of Text or Lineart character rendering
428 * (unless a preference for this is set)
433 public void makePDBImage(ImageMaker.TYPE type)
437 makePDBImage(null, type, null,
438 BitmapImageSizing.defaultBitmapImageSizing());
439 } catch (ImageOutputException ioex)
441 Console.error("Unexpected error whilst writing " + type.toString(),
446 public void makePDBImage(File file, ImageMaker.TYPE type, String renderer,
447 BitmapImageSizing userBis) throws ImageOutputException
449 int width = getWidth();
450 int height = getHeight();
452 BitmapImageSizing bis = ImageMaker.getScaleWidthHeight(width, height,
454 float usescale = bis.scale();
455 int usewidth = bis.width();
456 int useheight = bis.height();
457 ImageWriterI writer = new ImageWriterI()
460 public void exportImage(Graphics g) throws Exception
462 Graphics2D ig2 = (Graphics2D) g;
463 ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
464 RenderingHints.VALUE_ANTIALIAS_ON);
465 if (type == TYPE.PNG && usescale > 0.0f)
467 // for a scaled image, this scales down a bigger image to give the
471 ig2.scale(1 / usescale, 1 / usescale);
475 jmb.jmolViewer.requestRepaintAndWait("image export");
476 jmb.jmolViewer.renderScreenImage(ig2, usewidth, useheight);
479 String view = MessageManager.getString("action.view")
480 .toLowerCase(Locale.ROOT);
481 final ImageExporter exporter = new ImageExporter(writer,
482 getProgressIndicator(), type, getTitle());
484 final Throwable[] exceptions = new Throwable[1];
485 exceptions[0] = null;
486 final AppJmol us = this;
487 Runnable exportRunnable = () -> {
490 exporter.doExport(file, us, width, height, view, renderer, userBis);
491 } catch (Throwable t)
493 Console.debug("Problem when exporting structure image", t);
499 if (Jalview.isHeadlessMode())
501 exportRunnable.run();
505 Thread runner = Executors.defaultThreadFactory()
506 .newThread(exportRunnable);
512 } while (runner.isAlive() && time++ < 4000);
516 throw new ImageOutputException(
517 "Jmol took too long to export. Waited for 100 seconds.");
520 } catch (Throwable e)
522 throw new ImageOutputException(
523 "Unexpected error when generating image", e);
525 if (exceptions[0] != null)
527 if (exceptions[0] instanceof ImageOutputException)
529 throw ((ImageOutputException) exceptions[0]);
533 throw new ImageOutputException(
534 "Unexpected error when generating image", exceptions[0]);
540 public void showHelp_actionPerformed()
544 BrowserLauncher // BH 2018
545 .openURL("http://wiki.jmol.org");// http://jmol.sourceforge.net/docs/JmolUserGuide/");
546 } catch (Exception ex)
549 .errPrintln("Show Jmol help failed with: " + ex.getMessage());
554 public void showConsole(boolean showConsole)
558 if (splitPane == null)
560 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
561 splitPane.setTopComponent(renderPanel);
562 splitPane.setBottomComponent(scriptWindow);
563 this.getContentPane().add(splitPane, BorderLayout.CENTER);
564 splitPane.setDividerLocation(getHeight() - 200);
565 scriptWindow.setVisible(true);
566 scriptWindow.validate();
567 splitPane.validate();
573 if (splitPane != null)
575 splitPane.setVisible(false);
580 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
586 class RenderPanel extends JPanel
588 final Dimension currentSize = new Dimension();
591 public void paintComponent(Graphics g)
593 getSize(currentSize);
595 if (jmb != null && jmb.hasFileLoadingError())
597 g.setColor(Color.black);
598 g.fillRect(0, 0, currentSize.width, currentSize.height);
599 g.setColor(Color.white);
600 g.setFont(new Font("Verdana", Font.BOLD, 14));
601 g.drawString(MessageManager.getString("label.error_loading_file")
602 + "...", 20, currentSize.height / 2);
603 StringBuffer sb = new StringBuffer();
605 for (int e = 0; e < jmb.getPdbCount(); e++)
607 sb.append(jmb.getPdbEntry(e).getId());
608 if (e < jmb.getPdbCount() - 1)
613 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
616 g.drawString(sb.toString(), 20, currentSize.height / 2
617 - lines * g.getFontMetrics().getHeight());
621 else if (jmb == null || jmb.jmolViewer == null
622 || !jmb.isFinishedInit())
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.retrieving_pdb_data"),
629 20, currentSize.height / 2);
633 jmb.jmolViewer.renderScreenImage(g, currentSize.width,
640 public AAStructureBindingModel getBinding()
646 public ViewerType getViewerType()
648 return ViewerType.JMOL;
652 protected String getViewerName()