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;
35 import java.util.concurrent.Callable;
36 import java.util.concurrent.CompletableFuture;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.Future;
40 import java.util.concurrent.FutureTask;
42 import javax.swing.JPanel;
43 import javax.swing.JSplitPane;
44 import javax.swing.SwingUtilities;
45 import javax.swing.event.InternalFrameAdapter;
46 import javax.swing.event.InternalFrameEvent;
48 import jalview.api.AlignmentViewPanel;
49 import jalview.bin.Console;
50 import jalview.datamodel.PDBEntry;
51 import jalview.datamodel.SequenceI;
52 import jalview.datamodel.StructureViewerModel;
53 import jalview.datamodel.StructureViewerModel.StructureData;
54 import jalview.gui.ImageExporter.ImageWriterI;
55 import jalview.gui.StructureViewer.ViewerType;
56 import jalview.io.exceptions.ImageOutputException;
57 import jalview.structure.StructureCommand;
58 import jalview.structures.models.AAStructureBindingModel;
59 import jalview.util.BrowserLauncher;
60 import jalview.util.ImageMaker;
61 import jalview.util.ImageMaker.TYPE;
62 import jalview.util.MessageManager;
63 import jalview.util.Platform;
64 import jalview.util.imagemaker.BitmapImageSizing;
66 public class AppJmol extends StructureViewerBase
68 // ms to wait for Jmol to load files
69 private static final int JMOL_LOAD_TIMEOUT = 20000;
71 private static final String SPACE = " ";
73 private static final String QUOTE = "\"";
81 RenderPanel renderPanel;
90 * - add the alignment panel to the list used for colouring these
93 * - add the alignment panel to the list used for aligning these
95 * @param leaveColouringToJmol
96 * - do not update the colours from any other source. Jmol is
102 public AppJmol(StructureViewerModel viewerModel, AlignmentPanel ap,
103 String sessionFile, String viewid)
105 Map<File, StructureData> pdbData = viewerModel.getFileData();
106 PDBEntry[] pdbentrys = new PDBEntry[pdbData.size()];
107 SequenceI[][] seqs = new SequenceI[pdbData.size()][];
109 for (StructureData data : pdbData.values())
111 PDBEntry pdbentry = new PDBEntry(data.getPdbId(), null,
112 PDBEntry.Type.PDB, data.getFilePath());
113 pdbentrys[i] = pdbentry;
114 List<SequenceI> sequencesForPdb = data.getSeqList();
115 seqs[i] = sequencesForPdb
116 .toArray(new SequenceI[sequencesForPdb.size()]);
120 // TODO: check if protocol is needed to be set, and if chains are
122 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
123 pdbentrys, seqs, null);
125 jmb.setLoadingFromArchive(true);
126 addAlignmentPanel(ap);
127 if (viewerModel.isAlignWithPanel())
129 useAlignmentPanelForSuperposition(ap);
132 boolean useToColour = viewerModel.isColourWithAlignPanel();
133 boolean leaveColouringToJmol = viewerModel.isColourByViewer();
134 if (leaveColouringToJmol || !useToColour)
136 jmb.setColourBySequence(false);
137 seqColour.setSelected(false);
138 viewerColour.setSelected(true);
140 else if (useToColour)
142 useAlignmentPanelForColourbyseq(ap);
143 jmb.setColourBySequence(true);
144 seqColour.setSelected(true);
145 viewerColour.setSelected(false);
148 this.setBounds(viewerModel.getX(), viewerModel.getY(),
149 viewerModel.getWidth(), viewerModel.getHeight());
152 this.addInternalFrameListener(new InternalFrameAdapter()
155 public void internalFrameClosing(
156 InternalFrameEvent internalFrameEvent)
161 StringBuilder cmd = new StringBuilder();
162 cmd.append("load FILES ").append(QUOTE)
163 .append(Platform.escapeBackslashes(sessionFile)).append(QUOTE);
164 initJmol(cmd.toString());
168 protected void initMenus()
173 .setText(MessageManager.getString("label.colour_with_jmol"));
174 viewerColour.setToolTipText(MessageManager
175 .getString("label.let_jmol_manage_structure_colours"));
179 * display a single PDB structure in a new Jmol view
186 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
187 final AlignmentPanel ap)
189 setProgressIndicator(ap.alignFrame);
191 openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
196 private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
197 PDBEntry[] pdbentrys, SequenceI[][] seqs)
199 setProgressIndicator(ap.alignFrame);
200 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
201 pdbentrys, seqs, null);
202 addAlignmentPanel(ap);
203 useAlignmentPanelForColourbyseq(ap);
205 alignAddedStructures = alignAdded;
206 if (pdbentrys.length > 1)
208 useAlignmentPanelForSuperposition(ap);
211 jmb.setColourBySequence(true);
212 setSize(400, 400); // probably should be a configurable/dynamic default here
214 addingStructures = false;
215 worker = new Thread(this);
218 this.addInternalFrameListener(new InternalFrameAdapter()
221 public void internalFrameClosing(
222 InternalFrameEvent internalFrameEvent)
231 * create a new Jmol containing several structures optionally superimposed
232 * using the given alignPanel.
236 * - true to superimpose
240 public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
243 openNewJmol(ap, alignAdded, pe, seqs);
246 void initJmol(String command)
248 jmb.setFinishedInit(false);
249 renderPanel = new RenderPanel();
250 // TODO: consider waiting until the structure/view is fully loaded before
252 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
253 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
254 getBounds().width, getBounds().height);
255 if (scriptWindow == null)
257 BorderLayout bl = new BorderLayout();
260 scriptWindow = new JPanel(bl);
261 scriptWindow.setVisible(false);
264 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
266 // jmb.newJmolPopup("Jmol");
271 jmb.executeCommand(new StructureCommand(command), false);
272 jmb.executeCommand(new StructureCommand("set hoverDelay=0.1"), false);
273 jmb.setFinishedInit(true);
282 List<String> files = jmb.fetchPdbFiles(this);
283 if (files.size() > 0)
285 showFilesInViewer(files);
295 * Either adds the given files to a structure viewer or opens a new viewer to
299 * list of absolute paths to structure files
301 void showFilesInViewer(List<String> files)
303 long lastnotify = jmb.getLoadNotifiesHandled();
304 StringBuilder fileList = new StringBuilder();
305 for (String s : files)
307 fileList.append(SPACE).append(QUOTE)
308 .append(Platform.escapeBackslashes(s)).append(QUOTE);
310 String filesString = fileList.toString();
312 if (!addingStructures)
316 initJmol("load FILES " + filesString);
317 } catch (OutOfMemoryError oomerror)
319 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
320 Console.debug("File locations are " + filesString);
321 } catch (Exception ex)
323 Console.error("Couldn't open Jmol viewer!", ex);
324 ex.printStackTrace();
330 StringBuilder cmd = new StringBuilder();
331 cmd.append("loadingJalviewdata=true\nload APPEND ");
332 cmd.append(filesString);
333 cmd.append("\nloadingJalviewdata=null");
334 final StructureCommand command = new StructureCommand(cmd.toString());
335 lastnotify = jmb.getLoadNotifiesHandled();
339 jmb.executeCommand(command, false);
340 } catch (OutOfMemoryError oomerror)
342 new OOMWarning("When trying to add structures to the Jmol viewer!",
344 Console.debug("File locations are " + filesString);
346 } catch (Exception ex)
348 Console.error("Couldn't add files to Jmol viewer!", ex);
349 ex.printStackTrace();
354 // need to wait around until script has finished
355 int waitMax = JMOL_LOAD_TIMEOUT;
358 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
359 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
360 && jmb.getStructureFiles().length == files.size()))
364 Console.debug("Waiting around for jmb notify.");
365 waitTotal += waitFor;
367 // Thread.sleep() throws an exception in JS
368 Thread.sleep(waitFor);
369 } catch (Exception e)
372 if (waitTotal > waitMax)
374 System.err.println("Timed out waiting for Jmol to load files after "
376 // System.err.println("finished: " + jmb.isFinishedInit()
377 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
378 // + "; files: " + files.toString());
379 jmb.getStructureFiles();
384 // refresh the sequence colours for the new structure(s)
385 for (AlignmentViewPanel ap : _colourwith)
387 jmb.updateColours(ap);
389 // do superposition if asked to
390 if (alignAddedStructures)
392 alignAddedStructures();
394 addingStructures = false;
398 * Queues a thread to align structures with Jalview alignments
400 void alignAddedStructures()
402 javax.swing.SwingUtilities.invokeLater(new Runnable()
407 if (jmb.jmolViewer.isScriptExecuting())
409 SwingUtilities.invokeLater(this);
413 } catch (InterruptedException q)
420 alignStructsWithAllAlignPanels();
428 * Outputs the Jmol viewer image as an image file, after prompting the user to
429 * choose a file and (for EPS) choice of Text or Lineart character rendering
430 * (unless a preference for this is set)
435 public void makePDBImage(ImageMaker.TYPE type)
438 makePDBImage(null, type, null,
439 BitmapImageSizing.nullBitmapImageSizing());
440 } catch (ImageOutputException ioex) {
441 Console.error("Unexpected error whilst writing "+type.toString(),ioex);
445 public void makePDBImage(File file, ImageMaker.TYPE type, String renderer,
446 BitmapImageSizing userBis) throws ImageOutputException
448 int width = getWidth();
449 int height = getHeight();
451 BitmapImageSizing bis = ImageMaker.getScaleWidthHeight(width, height,
453 float usescale = bis.scale;
454 int usewidth = bis.width;
455 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.antialiased = true;
476 jmb.jmolViewer.requestRepaintAndWait("image export");
477 jmb.jmolViewer.renderScreenImage(ig2, usewidth, useheight);
480 String view = MessageManager.getString("action.view")
481 .toLowerCase(Locale.ROOT);
482 final ImageExporter exporter = new ImageExporter(writer,
483 getProgressIndicator(), type, getTitle());
485 final Throwable[] exceptions = new Throwable[1];
486 exceptions[0] = null;
487 final AppJmol us = this;
490 Thread runner = Executors.defaultThreadFactory().newThread(new Runnable()
497 exporter.doExport(file, us, width, height, view, renderer,
499 } catch (Throwable t)
506 do { Thread.sleep(25); } while (runner.isAlive());
507 } catch (Throwable e)
509 throw new ImageOutputException(
510 "Unexpected error when generating image", e);
512 if (exceptions[0] != null)
514 if (exceptions[0] instanceof ImageOutputException)
516 throw ((ImageOutputException) exceptions[0]);
520 throw new ImageOutputException(
521 "Unexpected error when generating image", exceptions[0]);
527 public void showHelp_actionPerformed()
531 BrowserLauncher // BH 2018
532 .openURL("http://wiki.jmol.org");// http://jmol.sourceforge.net/docs/JmolUserGuide/");
533 } catch (Exception ex)
535 System.err.println("Show Jmol help failed with: " + ex.getMessage());
540 public void showConsole(boolean showConsole)
544 if (splitPane == null)
546 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
547 splitPane.setTopComponent(renderPanel);
548 splitPane.setBottomComponent(scriptWindow);
549 this.getContentPane().add(splitPane, BorderLayout.CENTER);
550 splitPane.setDividerLocation(getHeight() - 200);
551 scriptWindow.setVisible(true);
552 scriptWindow.validate();
553 splitPane.validate();
559 if (splitPane != null)
561 splitPane.setVisible(false);
566 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
572 class RenderPanel extends JPanel
574 final Dimension currentSize = new Dimension();
577 public void paintComponent(Graphics g)
579 getSize(currentSize);
581 if (jmb != null && jmb.hasFileLoadingError())
583 g.setColor(Color.black);
584 g.fillRect(0, 0, currentSize.width, currentSize.height);
585 g.setColor(Color.white);
586 g.setFont(new Font("Verdana", Font.BOLD, 14));
587 g.drawString(MessageManager.getString("label.error_loading_file")
588 + "...", 20, currentSize.height / 2);
589 StringBuffer sb = new StringBuffer();
591 for (int e = 0; e < jmb.getPdbCount(); e++)
593 sb.append(jmb.getPdbEntry(e).getId());
594 if (e < jmb.getPdbCount() - 1)
599 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
602 g.drawString(sb.toString(), 20, currentSize.height / 2
603 - lines * g.getFontMetrics().getHeight());
607 else if (jmb == null || jmb.jmolViewer == null
608 || !jmb.isFinishedInit())
610 g.setColor(Color.black);
611 g.fillRect(0, 0, currentSize.width, currentSize.height);
612 g.setColor(Color.white);
613 g.setFont(new Font("Verdana", Font.BOLD, 14));
614 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
615 20, currentSize.height / 2);
619 jmb.jmolViewer.renderScreenImage(g, currentSize.width,
626 public AAStructureBindingModel getBinding()
632 public ViewerType getViewerType()
634 return ViewerType.JMOL;
638 protected String getViewerName()